C++ - how to find the length of an integer

后端 未结 13 1426
你的背包
你的背包 2020-12-09 10:03

I\'m trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use

13条回答
  •  无人及你
    2020-12-09 10:19

    Closed formula for the longest int (I used int here, but works for any signed integral type):

    1 + (int) ceil((8*sizeof(int)-1) * log10(2))
    

    Explanation:

                      sizeof(int)                 // number bytes in int
                    8*sizeof(int)                 // number of binary digits (bits)
                    8*sizeof(int)-1               // discount one bit for the negatives
                   (8*sizeof(int)-1) * log10(2)   // convert to decimal, because:
                                                  // 1 bit == log10(2) decimal digits
        (int) ceil((8*sizeof(int)-1) * log10(2))  // round up to whole digits
    1 + (int) ceil((8*sizeof(int)-1) * log10(2))  // make room for the minus sign
    

    For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".

    If you want the number of decimal digits of some int value, you can use the following function:

    unsigned base10_size(int value)
    {
        if(value == 0) {
            return 1u;
        }
    
        unsigned ret;
        double dval;
        if(value > 0) {
            ret = 0;
            dval = value;
        } else {
            // Make room for the minus sign, and proceed as if positive.
            ret = 1;
            dval = -double(value);
        }
    
        ret += ceil(log10(dval+1.0));
    
        return ret;
    }
    

    I tested this function for the whole range of int in g++ 9.3.0 for x86-64.

提交回复
热议问题