R
Richard Heathfield
Daniel Kraft said:
Well, you mean CHAR_BIT, but yes, that will give you the total number of
bits occupied by the int - including the sign bit, at least (but possibly
more than) 15 value bits, and at least (but possibly more than) no padding
bits.
Yes, CHAR_BIT gives the number of bits in a char, and a char is exactly one
byte wide, and every object must be a whole number of bytes wide. If
CHAR_BIT is 9, then objects must be a multiple of 9 bits wide.
The usual way to implement a "bit array", though, is as follows:
1) decide how many bits, B, you want your array to have (if you decide this
at runtime, you'll need to allocate the memory in step 2 dynamically,
check that you've got it, and release it when you're done);
2) allocate (B + CHAR_BIT - 1) / CHAR_BIT bytes (unsigned char foo[N] = {0}
or unsigned char *foo = calloc((B + CHAR_BIT - 1) / CHAR_BIT, 1),
initialising it all to 0 (you can use = {0} unless you allocate
dynamically, in which case use calloc - one of the rare occasions where
this is a good idea);
3) use macros to get, set, and test individual bits.
http://www.snippets.org has some macros that can be used for this purpose.
Hi,
I do need to implement something similar to C++'s std::bitset in C; for
this, I use an array of int's to get together any desired number of
bits, possibly larger than 32/64 or anything like this.
So of course it does not matter how many bits a single int has, but I do
need a reliable way to find it out.
I think of something like
CHAR_BITS*sizeof(int)
will do the trick, am I right here?
Well, you mean CHAR_BIT, but yes, that will give you the total number of
bits occupied by the int - including the sign bit, at least (but possibly
more than) 15 value bits, and at least (but possibly more than) no padding
bits.
I'm just confused that it is *CHAR*_BITS; in reference to the usual
example, there are some machines where char's have 9 bits--but is in
this case int required to have some multiple of 9 bits, too?
Yes, CHAR_BIT gives the number of bits in a char, and a char is exactly one
byte wide, and every object must be a whole number of bytes wide. If
CHAR_BIT is 9, then objects must be a multiple of 9 bits wide.
The usual way to implement a "bit array", though, is as follows:
1) decide how many bits, B, you want your array to have (if you decide this
at runtime, you'll need to allocate the memory in step 2 dynamically,
check that you've got it, and release it when you're done);
2) allocate (B + CHAR_BIT - 1) / CHAR_BIT bytes (unsigned char foo[N] = {0}
or unsigned char *foo = calloc((B + CHAR_BIT - 1) / CHAR_BIT, 1),
initialising it all to 0 (you can use = {0} unless you allocate
dynamically, in which case use calloc - one of the rare occasions where
this is a good idea);
3) use macros to get, set, and test individual bits.
http://www.snippets.org has some macros that can be used for this purpose.