Originally Posted by
Dave_Sinkula
Certainly not me, which is why my first post in that thread used a value-based expression that can resolve into a compile-time constant for the highest bit of an unsigned int.
I assume you mean this expression:
Code:
char binary[sizeof(value) * CHAR_BIT + 1];
In which case it's still not portable, but there's nothing wrong with it either. The reason it isn't portable is because sizeof takes the size of an expression from the type of the expression's result. So the above sizeof expression is equivalent to
Code:
sizeof ( int ) * CHAR_BIT + 1
Precisely what you were warning against in your little nitpick. The reason is isn't wrong is because you don't need the exact number of bits for a bitwise operation, you simply need enough memory to hold the upper bound number of bits in an integer, which the expression sizeof ( int ) * CHAR_BIT handles quite nicely.
The only way I know of to get the number of value bits is a run-time loop that relies on the fact that the bitwise operators only work with value bits:
Code:
#include <limits.h>
#include <stdio.h>
unsigned int value_bits ( void )
{
unsigned int n = 1U;
unsigned int value = UINT_MAX;
while ( ( value >>= 1U ) != 0 )
++n;
return n;
}
int main ( void )
{
printf ( "value_bits: %u\n", value_bits() );
return 0;
}