假设我有这样的位图:
sizeofBitmapInBits = 16; // must be multiple of 8
char* bitmap = new char[sizeofBitmapInBits/8](); // 2 bytes
我想切换这个位图中的一个位,比方说位 n° 11。
这是正确的吗?
int numBit = 11;
int posBitmap = floor(numBit / 8); // this gives me the byte in the bitmap
char ch = bitmap[posBitmap];
int positionInByte = numBit - posBitmap * 8 ; // this gives me the bit in the byte
ch |= 1 << positionInByte; // or ch |= 0 << positionInByte
bitmap[posBitmap] = ch;
最佳答案
它看起来基本上是正确的,但它比需要的要复杂一点。我要做的唯一技术更改是使用 unsigned char
而不是 char
。除此之外,你不需要floor
,你可以使用%
来计算位偏移量:
int index = numBit / 8;
int offset = numBit % 8;
bitmap[offset] |= 1 << offset;
正如@graygoose124 指出的那样,它会打开一点,但不会关闭它。要切换它,请将 |=
替换为 ^=
。更一般地,使用
bitmap[index] |= 1 << offset;
打开一点,然后
bitmap[index] &= ~(1 << offset);
关闭一点,然后
bitmap[index] ^= 1 << offset;
切换一下。
关于c++ - 在字符位图中切换一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198886/