Number of bits in a data type

后端 未结 6 1954
半阙折子戏
半阙折子戏 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:35

    Are you sure you want number of bits, not number of bytes? In C, for a given type T, you can find the number of bytes it takes by using the sizeof operator. The number of bits in a byte is CHAR_BIT, which usually is 8, but can be different.

    So, given a type T, the number of bits in an object of type T is:

    #include 
    size_t nbits = sizeof(T) * CHAR_BIT
    

    Note that, except for unsigned char type, all possible combinations of nbits bits above may not represent a valid value of type T.

    For the second part, note that you can apply sizeof operator to an object as well as a type. In other words, given a type T and an object x of such type:

    T x;
    

    You can find the size of T by sizeof(T), and the size of x by sizeof x. The parentheses are optional if sizeof is used for an object.

    Given the information above, you should be able to answer your second question. Ask again if you still have issues.

提交回复
热议问题