Why does sys.maxint == “7fffffffffffffff”?

``````>>> import sys
>>> print '{0:64b}'.format(sys.maxint)
111111111111111111111111111111111111111111111111111111111111111
>>> print '{0:16x}'.format(sys.maxint)
7fffffffffffffff
``````

What? Where did the 7 come from?

This doesn't fit my understanding of 2's complement either.

• The leading bit is the sign bit, hence all bits below that being set is the largest integer value allowed. – bigwillydos Apr 16 at 16:38
• It's a definition: `111111111111111111111111111111111111111111111111111111111111111` in binary is `9223372036854775807` in base 10 (decimal) and is equivalently `7fffffffffffffff` in hexadecimal. – not link Apr 16 at 16:39
• Is this asking "why is my maxint equal to 2^63-1, and not a rounder number like 2^64?", or is it asking "why does the hexadecimal representation of 2**(4*k+3)-1 for all positive integer values of k always start with a 7?", or is it asking something else? – Kevin Apr 16 at 16:42
• 7 = 1100, How does that make the leap to -1? – user48956 Apr 16 at 16:43
• Note that `7f = 127` – Norrius Apr 16 at 16:49

Count the number of 1's in the binary representation. There are 63 of them. Let's write 64 bits so we can see the leading 0:

``````0111111111111111111111111111111111111111111111111111111111111111
``````

That is the maximum 64-bit integer: 63 1 bits with the 64th bit 0. If the leftmost bit were a 1, we'd have `-1`. Oh dear! When the sign bit is 1 we get negative numbers. That's no good. 64 1's is just too many.

The above, in groups of 4:

``````0111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
``````

And in hex:

``````0111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
7    f    f    f    f    f    f    f    f    f    f    f    f    f    f    f
``````

In 2's complement, the highest positive number that can be represented with `N` bits is `0` followed by `N-1` `1`'s. Setting all `N` bits to `1` produces the representation of `-1`.

So on a 64-bit system, the maximum integer is 63 1-bits. In hex that will be `7` followed by 7 `f`'s.

In the 64 bit representation, the highest number which can be represent is `2^63-1`,

``````>>> import sys
>>> sys.maxint
9223372036854775807
>>> hex(9223372036854775807)
'0x7fffffffffffffff'
>>> (2**63)-1
9223372036854775807L
``````

It holds true for any N bit representation. E.g for 8 bits, maximum value is `2^7-1`

``````>>> hex(127)
'0x7f'
>>> hex(128)
'0x80'
``````

What? Where did the 7 come from?

The result of this line of code:

``````print '{0:64b}'.format(sys.maxint)
``````

Doesn't show you the leading 0. It is really `0b0111111111111111111111111111111111111111111111111111111111111111` which is `0x7fffffffffffffff`

The leading bit is the sign bit. Thus, the largest number you can have for a 64-bit integer on the system you ran this code on is having all bits below that set.

• use format 064b to show it – wim Apr 16 at 19:38