0

I am creating a chess program and for the board representation I am using bitboards. The bitboard for white pawns looks like this:

whitePawns=0x000000000000FF00;

Now, if I want to move the white pawn on the square D4, I would have to shift the 12th bit by either 8 or 10 places so that it can get on to the next rank. I want to shift the 12th bit without disturbing the positions of the remaining bits. How do I do that?

After shifting the whitePawns variable should look this:

whitePawns=0x0000000008F700;

3

2 Answers 2

3

Rather than shifting the bit, you can remove 1 from the old position, and put it in the new position.

For example, if you know that the bit at position 5 is set, and the bit at position 12 is not set, and you want to shift the fifth bit to the 12-th position, you can do it with a single XOR:

whitePawns ^= ((1 << 5) | (1 << 12)); 

The way this works is that XOR-ing a value with a mask "flips" all bits of the value marked by 1s in the mask. In this case, the mask is constructed to have 1s in positions 5 and 12. When you XOR it with the positions, the 1 in fifth position becomes zero, and zero in the 12-th position becomes 1.

Sign up to request clarification or add additional context in comments.

2 Comments

Will this work if the bit at position 12 is set? What will be the modification in that case?
@RohitShinde If the bit at position 12 is set, this will not work, because XOR flips bits marked by 1s. If you want to reset a bit to zero, use v &= ~(1<<i). To set a bit unconditionally, use v |= (1<<i). The reason I thought that XOR would work nicely is that a piece cannot replace a piece of the same color in chess.
1

I think you don't want a shift, you want to swap to bits. Try turning bit A off and then turning bit B on. Something like this:

whitePawns &= ~(1 << A); // Turn bit A off whitePawns |= (1 << B); // Turn bit B on 

Where A and B are the positions of the bits you want to swap.

EDIT: Whether the move is valid or not is another story, make the move only if bit B is NOT set (and probably other conditions):

if (!(whitePawns & (1 << B))) { // Make the swap. } 

1 Comment

This solution partially approaches what I have in mind. What if the bit I want to move my pawn to, is set? In that case I cannot swap. I just want to shift a bit in position to A to position B. It has to overwrite the value of bit B. Whatever be its value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.