I'm transferring my chess engine from C# to C++ to get a higher performance. I am using bitboards (unsigned long long's) for each chess piece, representing where they are located. So when looking bitwise at one of these unsigned long longs each one represents a piece, each zero an empty square.
I start with sending the unsigned long long array entry representing a piece to another unsigned long long: unsigned long long r = position[2]
When I count the "1's" in r my method returns 2, which means there are two bishops, that is true.
while r != 0
{
// I have been using a method which counts the Trailing zeros, p locates where the first "1" lies:
unsigned long long i = r;
unsigned long long y;
unsigned long long n = 63;
y = i << 32; if (y != 0) { n = n - 32; i = y; }
y = i << 16; if (y != 0) { n = n - 16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
int p = n - ((i << 1) >> 63);
/*The method works and for example returns 58 for the bishops, meaning the first bishop is situated on square 59. Then I'm doing stuff with this position, to estimate the possible moves of that piece, but that doesn't matter here.
Next, and that is where the problem occurs, I take away the first '1' from r:
*/
r -= (1UL << p)
}
When I now count the "1's" in r my method returns 33, while it should return one, as I subtracted one of the two bishops. The most curious thing is that when I use the same code in C# (with slighly changes, unsigned long long is ulong, etc.) the method works.
I tried to use different data types for p or deleted the "UL" in "(1UL << p)". But I couldn't think of any problems with the code. It seems to by a very simple silly mistake.