Algorithm to determine how many bytes are required to store int

sorry for the stupid question, but how could I figure out mathematically or use C ++ how many bytes would be required to store an integer.

+3
source share
10 answers

You can find the first force 2, which is greater than your number, and divide this power by 8, and then round the number to the nearest integer. Thus, for 1000, force 2 is equal to 1024 or 2 ^ 10; divide 10 by 8 to get 1.25, and round to 2. You need two bytes to store 1000!

+9
source

If you mean information theory , the easy answer is:

log(number) / log(2)

( , , - log(2), 2.)

, .

, , .:)

C ++ :

 char    1 byte
 short   2 bytes
 int     4 bytes
 long    8 bytes

, , , 4 8- .

+6

" int", sizeof(int) - .

" , ", . , , , 4, 3, 2 1 . , 16777216 4 , 65536-16777216 3 , 256-65535 2 0-255 1 . , 8 , 2 , 1 2 ^ 8, .. 256 ( 0, 0-255). , 2 2 ^ 16, .. 65536 ..

4 , int, . , , , , 1 , 1 2 .

, , , . , - , , - 8 , , 1 .

- .

int value = 23534; // or whatever
int bits = 0;

while (value)
{
    value >> 1;
    ++bits;
}
std::cout << "Bits used = " << bits << std::endl;
std::cout << "Bytes used = " << (bits / 8) + 1 << std::endl;
+3

, " x?" , , .

n- 2 n -1. , x, ceil (log 2 x) , .

, , . , log 10 123456 = 5.09151220..., ceil (log 10 (123456)) = 6, .

+2

sizeof(long int) = 4.

int nbytes( long int x )
{
  unsigned long int n = (unsigned long int) x;

  if (n <= 0xFFFF)
  {
    if (n <= 0xFF) return 1;
    else return 2;
  }
  else
  {
    if (n <= 0xFFFFFF) return 3;
    else return 4;
  }
}
+1

:

int bytes = (int)Math.Log(num, 256) + 1;

, , "" FP-. , , .

+1
/**
 * assumes i is non-negative.
 * note that this returns 0 for 0, when perhaps it should be special cased?
 */
int numberOfBytesForNumber(int i) {
    int bytes = 0;
    int div = 1;
    while(i / div) {
        bytes++;
        div *= 256;
    }
    if(i % 8 == 0) return bytes;
    return bytes + 1;
}
0
source

Try this code:

// works for num >= 0
int numberOfBytesForNumber(int num) {
   if (num < 0)
      return 0;
   else if (num == 0)
      return 1;
   else if (num > 0) {
      int n = 0;
      while (num != 0) {
        num >>= 8;
        n++;
      }
      return n;
   }
}
0
source

Since no one is running the simplest code that works, I also think:

unsigned int get_number_of_bytes_needed(unsigned int N) {
  unsigned int bytes = 0;
  while(N) { 
    N >>= 8;
    ++bytes;
  };
  return bytes;
};
0
source

This code runs on 447 million tests / sec on my laptop, where i= 1 to 1E9. iis a signed int:

n = (i > 0xffffff || i < 0) ? 4 : (i < 0xffff) ? (i < 0xff) ? 1 : 2 : 3;
0
source

All Articles