Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm to figure out how many bytes are required to hold an int

sorry for the stupid question, but how would I go about figuring out, mathematically or using c++, how many bytes it would take to store an integer.

like image 876
Anonymous Avatar asked Mar 17 '11 02:03

Anonymous


People also ask

How do you calculate the number of bytes in a number?

SORACOM uses the following for calculating byte conversion: 1 gigabyte (GB) = 1,024 megabytes (MB) 1 megabyte (MB) = 1,024 kilobytes (kB) 1 kilobyte (kB) = 1,024 bytes (B)

How many bytes would be needed to store the number?

Each integer is usually around 4 bytes of storage. So if you are storing the number in binary in the text file, and the binary equivalent is 1101110111010101, there are 16 integers in that binary number. 16 * 4 = 64. So your number will take up about 64 bytes of storage.


1 Answers

If you mean from an information theory point of view, then the easy answer is:

log(number) / log(2)

(It doesn't matter if those are natural, binary, or common logarithms, because of the division by log(2), which calculates the logarithm with base 2.)

This reports the number of bits necessary to store your number.

If you're interested in how much memory is required for the efficient or usual encoding of your number in a specific language or environment, you'll need to do some research. :)

The typical C and C++ ranges for integers are:

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

If you're interested in arbitrary-sized integers, special libraries are available, and every library will have its own internal storage mechanism, but they'll typically store numbers via 4- or 8- byte chunks up to the size of the number.

like image 138
sarnold Avatar answered Oct 02 '22 07:10

sarnold