How to determine how many bytes an integer needs?

前端 未结 22 1302
悲&欢浪女
悲&欢浪女 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: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.

    0 讨论(0)
  • 2020-12-13 03:15

    You need to raise 256 to successive powers until the result is larger than your value.

    For example: (Tested in C#)

    long long limit = 1;
    int byteCount;
    
    for (byteCount = 1; byteCount < 8; byteCount++) {
        limit *= 256;
        if (limit > value)
            break;
    }
    

    If you only want byte sizes to be powers of two (If you don't want 65,537 to return 3), replace byteCount++ with byteCount *= 2.

    0 讨论(0)
  • 2020-12-13 03:15

    A bit basic, but since there will be a limited number of outputs, can you not pre-compute the breakpoints and use a case statement? No need for calculations at run-time, only a limited number of comparisons.

    0 讨论(0)
  • 2020-12-13 03:16

    This will get you the number of bytes. It's not strictly the most efficient, but unless you're programming a nanobot powered by the energy contained in a red blood cell, it won't matter.

    int count = 0;
    while (numbertotest > 0)
    {
      numbertotest >>= 8;
      count++;
    }
    
    0 讨论(0)
提交回复
热议问题