C ++ using one byte to store two variables

I am working on a representation of a chessboard, and I plan to store it in an array with 32 bytes, where each byte will be used to store two parts. (Thus, only 4 bits are needed for each part)

By doing this in this way, there is overhead for accessing a specific board index. Do you think that this code can be optimized or you can use a completely different method of accessing indexes?

C ++

char getPosition(unsigned char* c, int index){
    //moving pointer
    c+=(index>>1);

    //odd number
    if (index & 1){
        //taking right part
        return *c & 0xF;
    }else
    {
        //taking left part
        return *c>>4;
    }
}


void setValue(unsigned char* board, char value, int index){
    //moving pointer
    board+=(index>>1);

    //odd number
    if (index & 1){
        //replace right part
                 //save left       value only 4 bits
        *board = (*board & 0xF0) + value;
    }else
    {
        //replacing left part
        *board  = (*board & 0xF) + (value<<4);
    }
}


int main() {

    char* c = (char*)malloc(32);

    for (int i = 0; i < 64 ; i++){
        setValue((unsigned char*)c, i % 8,i);
    }

    for (int i = 0; i < 64 ; i++){
        cout<<(int)getPosition((unsigned char*)c, i)<<" ";

        if (((i+1) % 8 == 0) && (i > 0)){
            cout<<endl;
        }


    }


    return 0;
}

I am also interested in your opinions regarding chess representations and optimizing the above method as an independent problem.

Thank you so much

EDIT

. , 64 . , , . . -, , , .

+3
6

. , 64 , 32. ? , , ?

, , AB D , , , , () * W * D. W = 100 D = 30, 3000 D. 64k 32k... ?

, , [location], .

AI , , - , . , - , , - , .

, ... . , , , , , .

+9

( ). , - :

   //taking left part
    return *c>>4;

* c , → . .. :

0b10100000 >> 4 == 0b11111010

(.. ++ , - , char ).

( , , , , ), [] ,

board[x][y] 

. . , , , .

+3

, 64 - . char [8] [8]. , . char [8] [8] ( ) .

( , ), , " " . , , inline.

+2

, ? , , , .

, , , , : getPosition return unsigned char "U" (, 0xF0U), , . , , - , ?

0

, , , , .

AFAIK, , 8 . 15 , L2 , RAM . , Expand() Reduce() : , . , , , , .

, , FPGA , .

0
source

As a chess player, I can tell you: there is more space than simply placing each piece. You should take into account some other things:

  • Which side should move on?
  • Could it be the white and / or black king of the king and / or the queen?
  • Is it possible to lay a pawn?
  • How many moves have passed since the last pawn move and / or capture?

If the data structure that you use to represent the position does not reflect this information, then you have big problems.

0
source

Source: https://habr.com/ru/post/1741513/


All Articles