Search code examples
c++c++11binarybitset

Bit representation not being printed correctly for long int


I am trying to print a bit representation of a long integer. I am using this variable as a bitboard for my chess program. However, the representation is not printed correctly. I am using the following code.

void displayBoard()
{

    bitset<64>x(fullBoard);
    cout<<x<<fullBoard<<endl;
    for(int i=0;i<64;i++)
    {
        if(fullBoard & (1<<i))
        {
            cout<<"1";
        }
        else
        {
            cout<<"0";
        }
    }

}  

The first two lines convert it to a binary representation using the bitset class and print it.

However, the when I try to do the same using the code in the for loop it gives me the following output:
1111111111111111000000000000000111111111111111110000000000000001
The correct output is:
1111111111111111000000000000000000000000000000001111111111111111

The value of fullBoard that I am using is: 0xFFFF00000000FFFF

I am compiling using C++11 using the following command: g++ board.cpp -std=c++11

Why is this code giving the wrong output? I do not think there is any error in the for loop.


Solution

  • I think the problem is here:

        if(fullBoard & (1<<i))
    

    This should be:

        if(fullBoard & (1ULL<<i))
    

    The reason being that 1<<i is evaluated as an int, which is probably 32 bits in your case, so it's UB once i exceeds 31. Making it 1ULL<<i forces the expression to be evaluated as 64 bits.