[英]Bitwise integer concationation
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. 在某些背景下,我试图编写一个系统以传递整数数据包,以便使用布尔切换来确定两个节点之间是否应有墙,以建立一个迷宫,目前我的迷宫可以处理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++;
}
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. 这是我目前正在构建的,我的想法是从一个int开始,根据布尔值“ _isWall”的返回值将该int传递给int,然后将结果移至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.
当int达到容量时,迭代到数组中的下一个int并再次开始,直到迷宫的墙填充了数组。
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?
我的按位运算似乎并未实际上将多个位分配给同一整数,我在哪里出错?
Use val | (1UL << temp2)
使用
val | (1UL << temp2)
val | (1UL << temp2)
, and not temp2 << 1
to set the bits. val | (1UL << temp2)
,而不是temp2 << 1
来设置位。 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. 您必须将整个字节初始化为零,并且只有在该值为true时才将其设置为1。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.