Macro for Bits in a Type
A macro to produce the number of bits used to represent a type in storage is:
#define CountBitsM(x) (sizeof (x) * CHAR_BIT)
However, this produces a result with type size_t
(usually). If you really need an int
result as stated in the question, convert it (but be aware overflow becomes possible):
#define CountBitsM(x) ((int) (sizeof (x) * CHAR_BIT))
Counting Bits
The second question asks to count the number of bits “to represent a type int
value” by shifting bits in an unsigned
value. There are two theoretical problems here. One is that the number of bits used to represent a value may including padding bits, and counting the bits by shifting a 1 through them only counts the value bits, not the padding bits. The second is that an int
may have more padding bits than an unsigned
; it may use fewer bits for the sign and value. Overwhelmingly, modern systems will not have these issues; the number of used bits in an int
will be the same as the total number of bits used to store it and the number of bits used in an unsigned
.
That said, you can count the number of bits in an unsigned
object with:
int count = 0;
for (unsigned u = 1; 0 != u; u <<= 1)
++count;
This repeatedly shifts the bit in u
left until it is shifted out, while counting the number of iterations required to do this. Note that the bits in an int
cannot properly be counted this way, because the behavior of left shift is not defined by the C standard when it overflows an int
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…