Bitwise integer concationation



对于某些背景,我正在尝试编写一个系统以传递整数包,以便使用布尔式切换来构建迷宫,以决定两个节点之间是否应该有墙,目前我的迷宫处理480堵墙,因此我不想发送带有单个项目的数据包,而是将其分为整数(长度8),从而给我480/8对象发送。

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++;
}

这是我当前构建的,我的想法是从INT开始,基于Bool" _iswall"的返回,然后将结果转移到INT的末尾。当int达到容量时,迭代到阵列中的下一个int,然后重新开始,直到迷宫的墙壁填充了数组。

编辑:缺乏我的要求。我的位操作实际上并未将多个位分配给同一整数,我要在哪里出错?

使用val | (1UL << temp2),而不是temp2 << 1设置位。稍后,您可以使用Bitwise &操作员查看是否设置了位。您必须将整个字节初始化为零,并仅在值为真时设置位。这是一个示例:

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("successn");
    else
        printf("failedn");
    return 0;
}

最新更新