c++chess

How to initialize bitboards in c++?


I've pored over the chess programming wiki on bit-boards, but i'm still struggling with how i'm supposed to actually create them. From what I've gathered they're supposed to be a uint64_t right? Sometimes I see them represented as long hex looking numbers like in stockfish, and other times I see them represented as a 64 digit binary number.

How do I take, for example, an array of chessboard positions and convert those into bit-boards for each piece and then two for color?


Solution

  • Since things like unsigned long long are not guaranteed to have any particular number of bits, making use of cstdint a good idea here, like so:

    #include <cstdint>
    uint64_t board;
    

    However, using std::bitset is likely to generate more readable code with less effort:

    #include <bitset>
    #include <cassert>
    
    class BitBoard {
     private:
      std::bitset<64> board;
     public:
      auto operator()(int x, int y){
        assert(0<=x && x<=7);
        assert(0<=y && y<=7);
        return board[8*y+x];
      }
      void setAll(bool val){
        if(val)
          board.set();   //All bits on
        else
          board.reset(); //All bits off
      }
    };
    
    int main(){
      BitBoard board;
    }
    

    I am not sure off-handedly which one would be more performant. Others have posted thoughts about performance here.