Gray code in .NET

后端 未结 5 1903
忘掉有多难
忘掉有多难 2021-01-03 01:05

Is there a built in Gray code datatype anywhere in the .NET framework? Or conversion utility between Gray and binary? I could do it myself, but if the wheel has already be

5条回答
  •  不知归路
    2021-01-03 01:16

    Here is a C# implementation that assumes you only want to do this on non-negative 32-bit integers:

    static uint BinaryToGray(uint num)
    {
        return (num>>1) ^ num;
    }
    

    You might also like to read this blog post which provides methods for conversions in both directions, though the author chose to represent the code as an array of int containing either one or zero at each position. Personally I would think a BitArray might be a better choice.

提交回复
热议问题