0

对于某些背景,我正在尝试编写一个系统来传递整数数据包,以便使用布尔切换来构建迷宫来决定两个节点之间是否应该有墙,目前我的迷宫处理 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 达到容量时,迭代到数组中的下一个 int 并重新开始,直到迷宫的墙壁填充了数组。

编辑:我所问的内容不清楚。我的按位运算似乎实际上并未将多个位分配给同一个整数,我哪里出错了?

4

1 回答 1

1

使用val | (1UL << temp2), 而不是temp2 << 1设置位。稍后您可以使用按位运算&符查看该位是否已设置。您必须将整个字节初始化为零并仅在值为真时设置该位。这是一个例子:

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;
}
于 2017-12-15T07:24:38.817 回答