在字符位图中切换位

Toggling a bit in a bitmap of chars

本文关键字:换位 位图 字符      更新时间:2023-10-16

假设我有这样一个位图:

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;

我看了一下,除了|=之外,几乎一切都井然有序。(虽然,我觉得可以更容易地做到)

目前,你的代码会打开一点,但如果你试图关闭它,什么也不会发生。(1 | 1 = 1, 1 | 0 = 1)

您应该使用^=,因为1 ^ 1 = 00 ^ 1 = 1

为了使它更简单,为什么不使用bitset (http://www.cplusplus.com/reference/bitset/bitset/):

#include <bitset>
std::bitset<16> bitmap;
int numBit = 11;
bitmap.flip(numBit);