繁体   English   中英

C# ulong 数据类型的二进制表示如何工作?

[英]How does the binary representation of a C# ulong data type work?

我目前正在尝试将ulong数据类型打印为 8x8 二进制位网格,因为ulong数据类型有 8 个字节 - 64 位。 在尝试这样做时,我一直在使用 32 位偏移量。 要了解我的问题,请查看以下内容。

当我打印这些位时,我希望它以这种方式格式化。

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

这是用于以这种方式打印位的两种相关方法。

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");
    }

使用这些方法,当我运行程序时,我得到了下面代码的 8x8 网格。

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

尽管十进制十六进制格式表明我将 2 作为存储在a中的数字,但 8x8 网格却没有。 为什么b5或第 34 位(从底部数)上的位打开? 当第 34 位打开时,变量a的值变为一个非常高的数字,而不是2

关于ulong数据类型的底层实现,我是否需要了解一些事情,或者我正在做的事情有什么问题?

任何意见或建议表示赞赏。

你会在这里找到答案: 什么是 1u? 答案是 int32 而不是您预期的 int64。

您只需在 getBit 方法中将 1u 替换为 1ul 即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM