You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# ulong类型二进制表示及位打印偏移问题排查

问题:ulong二进制位网格打印出现32位偏移错误

我正尝试将C#的ulong类型(8字节共64位)以8x8的二进制位网格形式打印,但始终出现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(@"    - - - - - - - -
    a b c d e f g h
");
    Console.WriteLine($"    Decimal: {board}
    Hexadecimal: {board:X}
");
}

测试代码及错误输出

测试代码:

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

问题原因

代码错误,和ulong底层实现无关。核心问题出在getBit方法中的1u:

  • 1u是uint类型(32位无符号整数),根据C#移位规则,无符号整数移位时,移位位数会对类型的位数取模(uint取模32)。
  • 当index >=32时,1u << index等价于1u << (index %32),导致高位的位判断错误,出现32位偏移的重复点亮(比如index=1和index=33会得到相同的掩码,所以两个位置都被错误点亮)。

修复方案

将1u替换为1UL(ulong类型的常量),确保移位操作基于64位无符号整数,避免循环移位问题:

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

同时,用!=0替代>0更符合位运算的逻辑习惯,因为位与运算的结果要么是0,要么是对应位的数值,非零即表示该位为1。

验证效果

修改后执行ulong a=0b10,输出会正确显示仅1行b列(对应index=1)为1,其余位置为0,符合预期。

内容的提问来源于stack exchange,提问作者mich abay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:15:39