转载自http://blog.csdn.net/v_july_v/article/details/6685962
July的文章看了很多。今天重新看了下这篇详细讲bitmap的文章。
bitmap挺有用的一个数据结构。
然后对照july的实现(基本一样,改了几个地方)
#include <iostream>
using namespace std;
const int BYTESIZE = 8;
void setBit(char *p, int pos)
{
for(int i=0; i<(pos/BYTESIZE); i++)
{
p++;
}
*p = *p | (0x01 << (pos%BYTESIZE));
return;
}
void Bitmaptest()
{
int num[] = {3, 5, 2, 10, 6, 12, 8, 14, 9};
const int BufferLen = 2;
char *pBuffer = new char[BufferLen];
memset(pBuffer, 0, BufferLen);
for(int i=0; i<9; i++)
{
setBit(pBuffer, num[i]);
}
for(int i=0; i<BufferLen; i++)
{
for(int j=0; j<BYTESIZE; j++)
{
if((*pBuffer&(0x01<<j)) == (0x01<<j))
{
cout << i*BYTESIZE +j << " ";
}
}
pBuffer ++;
}
}
int main()
{
Bitmaptest();
return 0;
}
一开始总以为July写错了,0x01<<j以为的方向,结果后来才发现自己理解错了。
在july博客中的例子((4,7,2,5,3)排序),图片形象表示的过程中,0在前面,7在后面。而写程序的时候,还是要0在后面,7在前面。所以0x01<<j用来判断第j位的数据。
另外我一个小小的补充,if((*pBuffer&(0x01<<j)) == (0x01<<j))这个判断改为if((*pBuffer>>j)&0x01)可以更简单些。
谢谢july的解释。