Home > Mobile >  How does the binary representation of a C# ulong data type work?
How does the binary representation of a C# ulong data type work?

Time:09-26

I'm currently trying to print a ulong data type as 8x8 grid of binary bits since the ulong data type has 8 bytes - 64 bits. While trying to do so, I keep getting a bit turned on with 32-bit offset. To understand my problem, look at the following.

When I print the bits, I would like for it to be formatted this way.

8 | 0 0 0 0 0 0 0 0
7 | 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0
5 | 0 0 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0
2 | 0 0 0 0 0 0 0 0
1 | 0 0 0 0 0 0 0 0
    - - - - - - - -
    a b c d e f g h

    Decimal: 0
    Hexadecimal: 0

These are the two relevant methods used to print the bits in that way.

public static bool getBit(ulong board, int index) => (board & (1u << (index))) > 0;

public static void printBoard(ulong board)
    {
        for (int i = 7; i >= 0; i--)
        {
            Console.Write($"{i   1} |");
            for (int j = 0; j < 8; j  )
            {
                Console.Write(" {0}", getBit(board, (i * 8)   j) ? 1 : 0);
            }
            Console.WriteLine();
        }
        Console.WriteLine("    - - - - - - - -\n    a b c d e f g h\n");
        Console.WriteLine($"    Decimal: {board}\n    Hexadecimal: {board:X}\n");
    }

Using these methods, when I run the program, I get this 8x8 grid for the following code.

ulong a = 0b10;
printBoard(a);
8 | 0 0 0 0 0 0 0 0
7 | 0 0 0 0 0 0 0 0
6 | 0 0 0 0 0 0 0 0
5 | 0 1 0 0 0 0 0 0
4 | 0 0 0 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0
2 | 0 0 0 0 0 0 0 0
1 | 0 1 0 0 0 0 0 0
    - - - - - - - -
    a b c d e f g h

    Decimal: 2
    Hexadecimal: 2

Although decimal and hexadecimal formats indicate that I have 2 as the number stored in a, the 8x8 grid doesn't. Why is the bit on b5 or the 34th bit(counting from the bottom) turned on? When the 34th bit is turned on, the value of the variable a changes to a very high number in place of 2.

Is there something I need to understand about the underlying implementation of the ulong data type or is there something wrong with what I'm doing?

Any advice or suggestion is appreciated.

CodePudding user response:

You'll find the answer here: what is 1u? The answer is an int32 and not an int64 as you expected.

You just have to replace 1u by 1ul in your getBit method.

  • Related