I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so:
int CountIntBitsF() {
If you want the number of bits used to store an int in memory, use Justin's answer, sizeof(int)*CHAR_BIT
. If you want to know the number of bits used in the value, use slebetman's answer.
Although to get the bits in an INT, you should probably use INT_MAX rather than UINT_MAX. I can't remember whether C99 actually guarantees that int
and unsigned int
are the same width, or just that they're the same storage size. I suspect only the latter, since in 6.2.6.2 we have "if there are M value bits in the signed type and N in the unsigned type, then M <= N", not "M = N or M = N-1".
In practice, integral types don't have padding bits in any implementation I've used, so you most likely get the same answer for all, +/- 1 for the sign bit.