【发布时间】:2021-06-23 00:40:17
【问题描述】:
问题
您好,这是我的第一个堆栈溢出问题。我正在使用 Bit-boards 来表示我的国际象棋引擎中的棋盘状态。目前我有一个像这样的位板类:
class Bitboard {
public:
uint64_t Board = 0ULL;
void SetSquareValue(int Square) {
Board |= (1ULL << Square);
}
void PrintBitbaord() {
for (int rank = 0; rank < 8; rank++) {
for (int file = 0; file < 8; file++) {
// formula for converting row and colum to index
// rank * 8 + file
int square = rank * 8 + file;
if (file == 0) {
cout << 8 - rank << " " << "|" << " ";
}
cout << (Board & (1ULL << square)) ? 1 : 0;
cout << " ";
}
cout << endl;
}
cout << " ---------------" << endl;
cout << " a b b d e f g h" << endl;
//cout << "current bitboard: " << self << endl;
}
};
我也有这个枚举(位于实际文件中的类上方):
enum BoardSquare {
a8, b8, c8, d8, e8, f8, g8, h8,
a7, b7, c7, d7, e7, f7, g7, h7,
a6, b6, c6, d6, e6, f6, g6, h6,
a5, b5, c5, d5, e5, f5, g5, h5,
a4, b4, c4, d4, e4, f4, g4, h4,
a3, b3, c3, d3, e3, f3, g3, h3,
a2, b2, c2, d2, e2, f2, g2, h2,
a1, b1, c1, d1, e1, f1, g1, h1
};
我的问题在于 set square value 方法调用:
TestBitboard.SetSquareValue(e2);
接着是:
TestBitboard.PrintBitboard();
给出一个奇怪的输出:
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 4503599627370496 0 0 0
1 | 0 0 0 0 0 0 0 0
---------------
a b c d e f g h
与我想要的输出相比:
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 1 0 0 0
1 | 0 0 0 0 0 0 0 0
---------------
a b c d e f g h
我希望在 cpp 和位操作方面有更多经验的人可以解释为什么我得到这个输出。虽然我对编程并不陌生,但我是 cpp 的新手,而且我以前从来没有搞乱过比特。
我尝试过的
我看过以下视频。我试图使用他们的类似功能的实现无济于事。
我还搞砸了代码交换值、尝试不同的枚举值等。
我能够得到的最大变化是值 4503599627370496 可以更改为不同的值,但仍然不是我想要的输出。
【问题讨论】:
-
有时查看十六进制数字确实很有帮助:4503599627370496 -> 0x10000000000000。我不知道这对你是否意味着什么,但它看起来确实很有趣。
-
不相关,但为什么列是
a b b d而不是a b c d?
标签: c++ bit-manipulation 64-bit bit bitboard