Bitwise integer concationation

97 views Asked by At

For some background, I'm trying to write a system to pass packets of integers for the purpose of building a maze using a boolean toggle to decide whether two nodes should have a wall between them, currently my maze handles 480 walls, therefore I don't want to send a packet with a single item, but rather split it into an array of integers (length 8) thus giving me 480/8 objects to send.

const int wallRows = mazeSize / 8;
int temp = NULL;
int temp2 = NULL;
int current = NULL;
int concatCount = 0;
int* walls = new int[wallRows];
int wallIndex = 0;

for (int i = 0; i < mazeSize; i++) {
    current = temp2;
    //ensure my ints have only 8 bytes
    if (concatCount >= 7) {
        //allocate a full int to the array
        walls[wallIndex] = temp;
        //clear the int
        temp = NULL;
        //move to the next array pos
        wallIndex++;
        //restart the int count
        concatCount = 0;
    }
    if (maze->allEdges[i]._iswall) {
        //append a 1 to the int
        temp = 0b1;
    }
    else {
        //append a 0 to the int
        temp = 0b0;
    }
    //increment the int count
    current = (temp2 << 1) | temp;
    concatCount++;
}

This is what I have currently built, my idea was to start with an int, pass it the int based on the return of the bool "_isWall" and bit shift the result onto the end of the int. When the int reaches capacity, iterate to the next int in the array and begin again until the maze's walls have populated the array.

Edit: lack of clarity on what I was asking. My bitwise operation does not appear to actually allocate multiple bits to the same integer, where am I going wrong?

1

There are 1 answers

0
Barmak Shemirani On

Use val | (1UL << temp2), and not temp2 << 1 to set the bits. Later you can use bitwise & operator to see if the bit is set. You must initialize the whole byte to zero and set the bit only if the value is true. Here is an example:

int main(void)
{
    //assign random values for testing
    int wallinfo[480];
    for(int i = 0; i < 480; i++)
        wallinfo[i] = !!(rand() % 2);

    //copy to the values to compress
    unsigned char compress[60] = { 0 };
    for(int i = 0; i < 60; i++)
        for(int j = 0; j < 8; j++)
            if(wallinfo[i * 8 + j])
                compress[i] |= 1UL << j;

    //decompress to get back wallinfo
    int decompress[480];
    for(int i = 0; i < 60; i++)
        for(int j = 0; j < 8; j++)
            decompress[i * 8 + j] = !!(compress[i] & (1UL << j));

    //wallinfo should match decompress
    if(memcmp(wallinfo, decompress, 480) == 0)
        printf("success\n");
    else
        printf("failed\n");

    return 0;
}