Afficher un message
Vieux 18/10/2007, 18h37   #8
Martin Wells
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Finding number of bits of integer

Daniel:

> I think of something like
> CHAR_BITS*sizeof(int)
> will do the trick, am I right here?



What you're looking for is the quantity of "value representational
bits". These are the bits that actually take place in arithmetic and
bit-shifting, and they are distinct from the other two varieties of
bits that can be present in an int type (i.e. the single sign bit and
the padding bits). On most systems, integer types don't have
padding... but the Standard permits that they may, which is why in
fully-portable programming you should shy away from
sizeof(unsigned)*CHAR_BIT for getting the VR bits.

The C Standard doesn't provide an operator or macro or anything for
determing the quantity of VR bits, but such a macro can be "own-
rolled". Of course, you can use a simple loop to work it out, but it's
a little trickier to get the figure as a compile-time constant (e.g.
for use in array dimensions).

A chap called Hallvard B Furuseth, (a genius if you ask me), devised a
macro called IMAX_BITS that's used for determing the amount of bits
you need to represent a given number, and he has it as a compile time
constant. (The only restriction is that the "given number" must be all
one's in binary: e.g. 1111, or 11111, or 111111). Given that the
highest number for any unsigned integer type will always be all-one's,
we can use this macro. Here's an example:

Quantity of value bits in unsigned short = IMAX_BITS(USHRT_MAX)

I've reshaped Hallvard's macro so that it can be used in the following
form:

Quantity of value bits in unsigned short = VALUE_BITS_UINT(unsigned
short)

The macro is a follows:

#define VALUE_BITS_UINT(my_type) (((my_type)-1) /
(((my_type)-1)%0x3fffffffL+1) \
/0x3fffffffL %0x3fffffffL *30 \
+ ((my_type)-1)%0x3fffffffL \
/(((my_type)-1)%31+1)/31%31*5 + 4-12/(((my_type)-1)%31+3))

Don't ask me how it works coz I haven't a clue. What I do know is that
it's tried and tested and definitely does work.

There's probably a way of getting the VR bits for a signed type also
but to be honest I've no interest in it because I shudder at the
thought of using signed types for bit manipulation.

Best of luck.

Martin

  Réponse avec citation
 
Page generated in 0,04987 seconds with 9 queries