Re[4]: [Dev-C++] using char* as bitfield
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <ca...@kr...> - 2003-09-30 10:25:33
|
hi Per,
Tuesday, September 30, 2003, 11:25:00 AM, you wrote:
> First:
> sizeof(mybits) is just size of pointer - not size of the array in bytes or
> bits.
yes, my fault. corrected. ;-)
> mybits[bit/8] |= 1 << (bit&3);
> isn't so complicated. Each character contains 8 bits. So by dividing bit
> with 8, I get which character the bit is stored in.
that was clear.
> bit&3 will use the 3 least significant bits for a numeric range of 0-7.
understood.
> 1 << (bit&3) will then access one of the 8 bits in the character.
ok. with you.
everything seems clear to me now. but the out put of my current code,
will be:
mybits: 0000 0000 0000 0000
mybits: 0400 0000 0000 0000
this does mean that the first byte changed from
(bin) 00000000 to
(bin) 00000100
right?
this should be
(bin) 0100000
(hex) 40
since I changed the second bit of all, right?
somewhere I made a mistake, I know, but where?
char *alloc_bits(unsigned int);
void set_bit(char*, unsigned int);
int get_bit(const char*, unsigned int);
void clear_bit(char*, unsigned int bit);
int main(int argc, char *argv[])
{
char *mybits;
mybits = alloc_bits(60);
if (mybits) printf("mybits: %X%X %X%X %X%X %X%X (%s)\n", *(mybits+0), *(mybits+1), *(mybits+2), *(mybits+3), *(mybits+4), *(mybits+5), *(mybits+6), *(mybits+7), mybits);
if (mybits) set_bit(mybits,2);
if (mybits) printf("mybits: %X%X %X%X %X%X %X%X (%s)\n", *(mybits+0), *(mybits+1), *(mybits+2), *(mybits+3), *(mybits+4), *(mybits+5), *(mybits+6), *(mybits+7), mybits);
system("PAUSE");
return 0;
}
char *alloc_bits(unsigned int bits)
{
return calloc(((bits+7)/8), sizeof(char));
}
void set_bit(char *bits,unsigned int bit)
{
bits[bit/8] |= 1 << (bit&3);
}
int get_bit(const char *bits, unsigned int bit)
{
return ((bits[bit/8] | (1 << (bit&3))) != 0) ? bit : 0;
}
void clear_bit(char *mybits,unsigned int bit) {
mybits[bit/8] &= ~(1 << (bit&3));
}
gruss
/Christian mailto:ca...@kr...
---
I propose that the following character sequence for joke markers:
:-)
19-Sep-82 11:44 Scott E Fahlman
|