How to determine how many bytes an integer needs?

前端 未结 22 1577
悲&欢浪女
悲&欢浪女 2020-12-13 02:13

I\'m looking for the most efficient way to calculate the minimum number of bytes needed to store an integer without losing precision.

e.g.

int: 10 = 1 byte
         


        
22条回答
  •  遥遥无期
    2020-12-13 03:05

    I think this is a portable implementation of the straightforward formula:

    #include 
    #include 
    #include 
    
    int main(void) {
        int i;
        unsigned int values[] = {10, 257, 67898, 140000, INT_MAX, INT_MIN};
    
        for ( i = 0; i < sizeof(values)/sizeof(values[0]); ++i) {
            printf("%d needs %.0f bytes\n",
                    values[i],
                    1.0 + floor(log(values[i]) / (M_LN2 * CHAR_BIT))
                  );
        }
        return 0;
    }
    

    Output:

    10 needs 1 bytes
    257 needs 2 bytes
    67898 needs 3 bytes
    140000 needs 3 bytes
    2147483647 needs 4 bytes
    -2147483648 needs 4 bytes

    Whether and how much the lack of speed and the need to link floating point libraries depends on your needs.

提交回复
热议问题