Search code examples
cbinarybit-manipulationchess

Is it possible to determine specific digits of 64 bit number in C


I'm trying to make a chess engine. I've done some reading and it seems like using a 64 bit number to represent the board is the way to go. However I'm a little confused, it seems that there's no easy way to write a number in binary, and I also can't find a way to select a digit in a number. For example if I do

    int aNum = 356;
    b = aNum[1];

Is there a way to do this so that I can set b equal to 5? In the program it'd be a binary number like 1001010101, and I'd like to find out where all of the 1s are when I go through there. For example if I have a rook and I'm looking for possible moves to the right, I would have it iterate through digits until it finds a 1.

Hopefully that was easy to understand, thank you!


The issue was a fundamental misunderstanding of why 64 bit numbers are used in chess engines. In reality the advantage is that if you want to check for items on squares you could do something like boardRep & 1 would check for an element on the first square of the board.


Solution

  • If you want to fetch a specific digit in the decimal representation of a 64-bit number (which is not what I think you want to do), you first have to create that decimal representation. The basic recipe would be something like this:

    uint64_t x = 123456789012345;
    char buf[30];
    snprintf(buf, sizeof(buf), "%lld", x);
    int digit5 = buf[5] - '0';
    printf("digit [5] = %d\n", digit5);
    

    This should print 6.

    Bear in mind, though, it's not a 64 digit number. (The largest 64-bit number has 20 decimal digits.)

    Perhaps you want to extract bit number n. To do that, you'll need some bitwise operations, perhaps something like this:

    int bit5 = (x >> 5) & 0x01;
    printf("bit 5 = %d\n", bit5);
    

    Or if you just want to test the bit, you can do

    if(x & (1 << 5)) printf("bit 5 is true\n");
    

    Or you can precompute some bitmasks:

    unsigned long long int masks[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, /* ... */ };
    
    if(x & masks[5]) printf("bit 5 is true\n");