2009년 10월 12일 월요일

비트 조작

실행결과)
10000
11000
11100
11110
11111

소스)
#include "stdafx.h"
#include <boost/utility.hpp>
#include <boost/pool/object_pool.hpp>
using namespace std;
using namespace boost;


// memory
// 1000 0000

// 1000 0000
// 0: first bit

// 0000 0001
// 7: last bit

class BitSet
{
public:
typedef vector<char> Buffer;
Buffer _buffer;
int _bitCount;
void resize(int bitCount)
{
int byteCount= (int)(ceil((float)bitCount/8));
_bitCount=bitCount;
_buffer.resize(byteCount);
memset(&_buffer.front(), 0,  byteCount);
}
BitSet()
{
}
~BitSet()
{
}
void setBit(int id, bool on)
{
ASSERT(0<=id && id< _bitCount);
ASSERT(0<_buffer.size());
int whichByte= id/ 8;
int whichBit= 7-id%8;
ASSERT(0<= whichByte && whichByte < (int)_buffer.size());
char& output= _buffer[whichByte];

output |= 1<<whichBit;
}

bool getBit(int id) const
{
ASSERT(0<=id && id< _bitCount);
ASSERT(0<_buffer.size());
int whichByte= id/ 8;
int whichBit= 7- id%8;
ASSERT(0<= whichByte && whichByte < (int)_buffer.size());
const char& input= _buffer[whichByte];
return input  & 1<<whichBit ? true: false;
}

int getBitCount()
{
return _bitCount;
}

string makeBinaryString()
{
int i;
string ret;
for (i=0;i<_bitCount;i++)
{
char b=getBit(i) ? '1':'0';
ret= ret+b;
}
return ret;
}
};

int main()
{
BitSet set;
set.resize(5);


int i;

for (i=0;i<set.getBitCount();i++)
{
set.setBit(i,true);
cout<<set.makeBinaryString()<<endl;
}

return 0;

}

댓글 없음:

댓글 쓰기