How to determine how many bytes an integer needs?

前端 未结 22 1607
悲&欢浪女
悲&欢浪女 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条回答
  •  旧时难觅i
    2020-12-13 03:13

    There are a multitude of ways to do this.

    Option #1.

     int numBytes = 0;
     do {
         numBytes++;
     } while (i >>= 8);
     return (numBytes);
    

    In the above example, is the number you are testing, and generally works for any processor, any size of integer.

    However, it might not be the fastest. Alternatively, you can try a series of if statements ...

    For a 32 bit integers

    if ((upper = (value >> 16)) == 0) {
        /* Bit in lower 16 bits may be set. */
        if ((high = (value >> 8)) == 0) {
            return (1);
        }
        return (2);
    }
    
    /* Bit in upper 16 bits is set */
    if ((high = (upper >> 8)) == 0) {
        return (3);
    }
    return (4);
    

    For 64 bit integers, Another level of if statements would be required.

    If the speed of this routine is as critical as you say, it might be worthwhile to do this in assembler if you want it as a function call. That could allow you to avoid creating and destroying the stack frame, saving a few extra clock cycles if it is that critical.

提交回复
热议问题