Bit representation not printing correctly for long int

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

void displayBoard()

    for(int i=0;i<64;i++)
        if(fullBoard & (1<<i))



The first two lines convert it to binary using the class bitset

and print it.

However, when I try to do the same with the code in the for loop, it gives me the following output:

Correct output:

The value fullBoard

I'm using:0xFFFF00000000FFFF

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

Why is this code giving incorrect output? I don't think there is any error in the for loop.


source to share

3 answers

I think the problem is here:

    if(fullBoard & (1<<i))


It should be:

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


The reason is that it 1<<i

evaluates to an int, which is probably 32 bits in your case, so the UB is one time i

greater than 31. Forcing it to 1ULL<<i

force the expression to evaluate to 64 bits.



ok, your loop looks great at first glance, but constant 1 is not a 64 bit integer, so you have to cast to unsigned long long.



"Why is this code giving incorrect output? I don't think there is any mistake in the for loop."

Well, as mentioned, in your for loop, your switch operation is definitely a bug. But the good news is you don't need this cycle for()

with what you already have.

"Correct conclusion:



The following code

unsigned long long fullBoard = 0xFFFF00000000FFFF;
std::bitset<64> x(fullBoard);
std::cout << x << std::endl;


works well for me, the output is as desired (see live example ):



While the above and other answers will be considered, you may have a problem with your undisclosed datatype fullBoard

My code example declares it as unsigned long long

smaller types are truncated 0xFFFF00000000FFFF

to 0x000000000000FFFF

. Note this to consistently output the output for fullBoard

and x




All Articles