How to determine how many bytes an integer needs?

前端 未结 22 1530
悲&欢浪女
悲&欢浪女 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 02:54

    You need just two simple ifs if you are interested on the common sizes only. Consider this (assuming that you actually have unsigned values):

    if (val < 0x10000) {
        if (val < 0x100) // 8 bit
        else // 16 bit
    } else {
        if (val < 0x100000000L) // 32 bit
        else // 64 bit
    }
    

    Should you need to test for other sizes, choosing a middle point and then doing nested tests will keep the number of tests very low in any case. However, in that case making the testing a recursive function might be a better option, to keep the code simple. A decent compiler will optimize away the recursive calls so that the resulting code is still just as fast.

提交回复
热议问题