在字符位图中切换位
Toggling a bit in a bitmap of chars
假设我有这样一个位图:
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 = 0
和0 ^ 1 = 1
。
为了使它更简单,为什么不使用bitset (http://www.cplusplus.com/reference/bitset/bitset/):
#include <bitset>
std::bitset<16> bitmap;
int numBit = 11;
bitmap.flip(numBit);
相关文章:
- C / C++ 移位/偏移/向左或向右移动位图?
- 如何在快板的屏幕中显示子位图的绘制?
- CreateDIBSection为同一图像返回不一致的位图位值
- C++ 位图中的 ttc 字体
- 使用 GDI+ 旋转位图,然后转换为 HDC
- 难以从 CImageList 设置菜单项位图
- 如何将位图拉伸到父面板(wxWidgets 自定义)
- 如何使用 freetype2 访问单色位图中的像素状态
- 将位图 (bmp) 转换为具有透明度的 png (Windows c++)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- 位图到垫子/2D 数组
- Gdiplus位图没有Alpha通道
- 如何从路径字符串加载Gdiplus::位图
- 在C++中使用Gdiplus创建透明位图
- 用C++压缩内存中的位图
- C++gdi::内存中的位图到PNG图像
- LoadImage 函数不适用于 ImageMagick 创建的位图图像
- (位图)LoadImage() 返回 NULL,GetLastError() 返回 0
- 将Qt qml文件转换为位图图像
- 在字符位图中切换位