在chars的位图中切换一点

时间:2013-04-24 17:50:23

标签: 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;

3 个答案:

答案 0 :(得分:3)

它看起来基本上是正确的,但它比它需要的要复杂一些。我所做的唯一技术变更是使用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 = 11 | 0 = 1

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

答案 2 :(得分:1)

为了使它更简单,然后@Pete Becker回答,为什么不使用bitset(http://www.cplusplus.com/reference/bitset/bitset/):

#include <bitset>
std::bitset<16> bitmap;

int numBit = 11;
bitmap.flip(numBit);