c++ - 在字符位图中切换一点

标签 c++ bitmap bit-manipulation

假设我有这样的位图:

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/

相关文章:

c++ - 将命令行参数传递给从 C++ 程序调用的 bash shell 脚本

c++ - 将抗锯齿图元绘制到位图 Allegro 5

c++ - 使用 COM Interop 来使用 DLL

c++ - 链表的数组实现

c++ - 控制台关闭时从 GUI 应用程序附加控制台

android - 将图像从 fragment 传递到 Activity - 获取空对象

c# - UIElement 屏幕截图 UWP - C#

python - 在 Python 3 中返回整数中最低有效位集的位置的最快方法是什么?

c++ - 按位运算截断数字的最后两位

javascript - 创建此号码的最快方法?