Number of bits in a data type

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

    In limits.h, UINT_MAX is the maximum value for an object of type unsigned int. Which means it is an int with all bits set to 1. So, counting the number of bits in an int:

    #include 
    
    int intBits () {
        int x = INT_MAX;
        int count = 2; /* start from 1 + 1 because we assume
                        * that sign uses a single bit, which
                        * is a fairly reasonable assumption
                        */
    
        /* Keep shifting bits to the right until none is left.
         * We use divide instead of >> here since I personally
         * know some compilers which does not shift in zero as
         * the topmost bit
         */
        while (x = x/2) count++;
    
        return count;
    }
    

提交回复
热议问题