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()
{

    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 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:
1111111111111111000000000000000111111111111111110000000000000001


Correct output:
1111111111111111000000000000000000000000000000001111111111111111

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.

+3


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.

+5


source


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.



+1


source


"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:

1111111111111111000000000000000000000000000000001111111111111111

      

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 ):

1111111111111111000000000000000000000000000000001111111111111111

      


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

.

0


source







All Articles