将棋盘转换为位掩码

时间:2014-02-09 15:06:47

标签: c++ bit-manipulation

我正在尝试将矩阵棋盘转换为无符号长整数。如果该位置有硬币我更新相应的掩码。继承我的代码

    unsigned long long int mask = 0;
    cout<<mask<<endl;
    for(int i=0;i<8;++i)
        for(int j=0;j<8;++j){
            int pos = i*8+j;
            cin>>board[i][j];
            if(board[i][j] == 'P')
                mask|=(1<<pos);
    }
     for(int i=0;i<8;++i)
     {
        for(int j=0;j<8;++j)
        {
            int pos = i*8+j;
            if(mask&(1<<pos))
                cout<<1;
            else
                cout<<0;

        }
        cout<<endl;
     }

但是当我提供以下输入时

........
...P....
.....P..
...P....
........
........
P......P
.......P

输出如下

00000000
00010000
10000101
00010001
00000000
00010000
10000101
00010001

这显然是错误的。但我似乎没有在这里发现任何错误。提前谢谢。

2 个答案:

答案 0 :(得分:7)

您需要在位操作代码中使用unsigned long long文字:

            mask|=(1ull<<pos);
                    ^^^

        if(mask&(1ull<<pos))
                  ^^^

如果您的编译器不支持ull后缀,则可能必须明确地将1强制转换为unsigned long long

P.S。如果您想知道当前代码如何最终产生输出,请观察输出由电路板的两半组成,或者打印两次。

答案 1 :(得分:1)

答案是双重的:

  • 您不应该使用unsigned long long开头。
  • 常量默认为int,您需要显式转换它们(或使用输入和命名的)

关于unsigned long long:无法保证其宽度足够,在旧平台/编译器上可能只有32位。因此,您应该:#include <cstdint>然后使用uint64_t

关于常量,您可以使用uint64_t(1),也可以只定义static uint64_t const Bit = 1;,然后在公式中使用Bit代替1

相关问题