Re[3]: [Dev-C++] using char* as bitfield
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-09-30 09:25:39
|
First:
sizeof(mybits) is just size of pointer - not size of the array in bytes or
bits.
mybits[bit/8] |=3D 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.
bit&3 will use the 3 least significant bits for a numeric range of 0-7.
1 << (bit&3) will then access one of the 8 bits in the character.
char test_bit(const char* mybits,unsigned bit) {
return (mybits[bit/8] | (1 << (bit&3))) !=3D 0;
}
char clear_bit(const char *mybits,unsigned bit) {
mybits[bit/8] &=3D ~(1 << (bit&3));
}
/Per W
On Tue, 30 Sep 2003, Christian Sch=E4fer wrote:
> hi Per,
>
> I'll show you my code now. somehow it does not work as planned..
>
> char *alloc_bits(unsigned int);
> void set_bit(char*, unsigned int);
>
> int main(int argc, char *argv[])
> {
> char *mybits;
>
> mybits =3D alloc_bits(60);
>
> if (mybits) printf("bits[%d]: %X\n",sizeof(mybits), *mybits);
>
> if (mybits) set_bit(mybits,2);
>
> if (mybits) printf("bits[%d]: %X\n",sizeof(mybits), *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] |=3D 1 << (bit&3);
> }
>
> what exactly does the set_bit() function do?
> I don't understand it fully especially the (bit&3) part.
> also I am totally lost in writing a get_bit() function..
>
> any help appreciated!
>
>
> gruss
> /Christian mailto:ca...@kr...
>
> ---
>
>
> I propose that the following character sequence for joke markers:
>
> :-)
>
> 19-Sep-82 11:44 Scott E Fahlman
>
>
>
> -------------------------------------------------------
> This sf.net email is sponsored by:ThinkGeek
> Welcome to geek heaven.
> http://thinkgeek.com/sf
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|