Python Can Do Infinite Binary Operations Per Second

…as long as infinity of them are the same

Andrew Taylor
2 min readOct 27, 2013

A few days ago I discovered something lovely that Python does with integers: they’re all arbitrary precision by default.

In C, for example, an ‘int’ is 32 bit and can store up to about two billion, and a ‘long’ is 64-bit and can store slightly over nine billion billion. That’s obviously plenty for any real-life programming except perhaps Cookie Clicker or hunting for a perfect cuboid, but in Python you can store any integer exactly, because its integers are essentially infinity-bit. So zero is infinite zeros, one is infinite zeros and a one, two is infinite zeros, a one and a zero, and so on.

In C, you can do ‘bitwise’ operations. 0011 ‘bitwise and’ 0101 is 0001 — because only digits where both numbers have a 1 are 1. By the same token, 0011 ‘bitwise or’ 0101 is 0111. In Python, you can do exactly that: the infinite strings of zeros don’t really figure so it ignores them, and 3 & 5 = 1 just like in C.

In C, you can bit-shift integers, which is the binary equivalent of adding or removing zeros to multiply or divide by ten. Python does this too. C has to add a new zero to the end. Python doesn’t, because there are already infinite of them.

In C, negative one is encoded by making all 32 digits of the binary integer ones. In negative two, the last one is a zero, and so on. Python does that too — except in Python, negative one is encoded as an infinite string of ones.

And you can bitwise operate on them. You can take ‘bitwise not’ of zero and get negative one. You can ask for (3 << 2) & ~5 and it will just go ahead and work it out.

It’s just a thoroughly lovely implementation of something completely straightforward once you wrap your head around it but completely mind-melting right up until that point.

--

--