Number of bits in a data type

后端 未结 6 1873
半阙折子戏
半阙折子戏 2021-02-06 14:53

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() {         


        
6条回答
  •  醉酒成梦
    2021-02-06 15:37

    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.

提交回复
热议问题