Search code examples
pythoncomputer-science

Understanding how plain integers are represented in Python


While reading about Python's built-in types of number and specifically integers, I came across this line as quoted below;

Plain integers are at least 32 bits long. The range is at least -2,147,483,648 to 2,147,483,647 (approximately ± 2 billion).

Does it mean that any arbitrary number that I can think of which has 2 billion digits, is the limit for Python to display it as a plain integer? If I should ask more specifically, what does "32 bits long" mean in reference to the aforementioned quoted sentence.


Solution

  • It's not 2 billion digits, but the actual value of 2 billion.

    The reference of 32 bit represents the number of bits that python can store a plain integer into. Bits are represented in the base of 2 (because a bit can either be 0 or 1), where as our more common numbers in base of 10 are represented in the base of 10. The number 1 in the base 2 is 1, but the number 2 in the base 2 is 10 - just as in the base of 10, we go from 9 to 10.

    The maximum value that can be stored in 32 bits are the number of combinations you can flip 32 ones or zeros. This will make the following number as 2^32 (=4 294 967 296). But you need to subtract 1 to get the maximum, because 0 is also a combination, making the largest unsigned number 4 294 967 295.

    To represent also negative numbers the first bit is often reserved for signing the integer (1 means negative, 0 means positive) so it's roughly divided in half, making the smallest number -2 147 483 648 and the largest 2 147 483 647.