69,371
社区成员
发帖
与我相关
我的任务
分享
// set the bit at position pos in the array bits to the value state
void set_bit(unsigned char* bits, unsigned int pos, unsigned int state)
{
unsigned char mask = 0x80; // = 128 dec = 10000000 bin
unsigned int j = pos % 8, k = pos / 8;
if(j)
mask >>= j; // shift bitmask to right
if (state)
bits[k] |= mask;
else
bits[k] &= (~mask);
}
// get the state of the bit at position pos in the array bits
unsigned int get_bit(const unsigned char* bits, unsigned int pos)
{
unsigned char mask = 0x80; // = 128 dec = 10000000 bin
unsigned int j = pos % 8;
if(j)
mask >>= j; // shift bitmask to right
return ((mask & bits[pos/8]) ? 1 : 0);
}
void cnvtbit(char *in, char *out, size_t len)
{
int i,j;
for(i=0;i<len;i+=8)
for(j=0;j<=7;j++)
{
if(i+j<len)
{
out[i/8] |= (in[i+j]<<(7-j));
}
else
{
break;
}
}
}
char in[18] = {1,0,0,1, 1,1,0,0, 1,1,0,1, 1,0,1,1, 0,1};
char out[3] = {0};
cnvtbit(in,out,18);