Reputation: 1603
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.
Upvotes: 3
Views: 228
Reputation: 1
"Why is this code giving the wrong output? I do not think there is any error in the for loop."
Well, as others mentioned, there certainly is an error in your for loop, your shift operation respectively. But the good news is, you don't need this for()
loop, with what you have at hand at already.
"The correct output is:"
1111111111111111000000000000000000000000000000001111111111111111
The following code
unsigned long long fullBoard = 0xFFFF00000000FFFF;
std::bitset<64> x(fullBoard);
std::cout << x << std::endl;
works well for me, output is as wanted (see live sample):
1111111111111111000000000000000000000000000000001111111111111111
Though, the above shown and the other answers considered, you might have a problem with your non disclosed data type of fullBoard
.
My code example declares it as unsigned long long
, smaller types will cut off 0xFFFF00000000FFFF
to 0x000000000000FFFF
. Note this to get output for fullBoard
and x
consistently.
Upvotes: 0
Reputation: 169
well your loop looks fine at the first glance, but the constant 1 is not a 64 bit integer, so you have to cast to to a unsigned long long.
Upvotes: 1
Reputation: 212979
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.
Upvotes: 5