### Arithmetic shift with Python

While reviewing a piece of source code at work I found something like this which I wasn’t very familiar with:

a = (1<<0) b = (1<<1) c = (1<<2) d = (1<<3) e = (1<<4) f = (1<<5) g = (1<<6) h = (1<<7) i = (1<<8) j = (1<<9) k = (1<<10)

What we have is called shifting, which is shifting integer values either from the left or to the right. In the example above, we shift the integer values on the right, to the left by 1. It’s so easy to understand yet I was confused about this.

To understand what’s going on, lets put our values above into dict, traverse through them in a for loop and print out their values:

>>> for i in sorted(test_dict.items()):

… print i

…

(‘a’, 1)

(‘b’, 2)

(‘c’, 4)

(‘d’, 8)

(‘e’, 16)

(‘f’, 32)

(‘g’, 64)

(‘h’, 128)

(‘i’, 256)

(‘j’, 512)

(‘k’, 1024)

>>>

The values in our dict looks familiar to me. Yup, its a binary system! (read here for more details: http://www.plcdev.com/plc_basics/number_systems_and_codes/binary_people_learning_your_1s_and_0s )

So why are our values 1 to 10 being printed out in the binary system? because the binary format of our integers are being shifted to the left by 1 place, like so:

>>> test_list = [a, b, c, d, e, f, g, h, i, j, k]

>>> for i in test_list:

… print i

…

1

2

4

8

16

32

64

128

256

512

1024

>>> for i in test_list:

… print bin(i)

…

0b1

0b10

0b100

0b1000

0b10000

0b100000

0b1000000

0b10000000

0b100000000

0b1000000000

0b10000000000

>>>

We can have a class file that will read in an integer of … say … 5? 5 will use this new binary system we declared and work out which variables from a to k is true and which are false. For example:

(‘a’, 1) True

(‘b’, 2) False

(‘c’, 4) True

(‘d’, 8) False

(‘e’, 16) False

(‘f’, 32) False

(‘g’, 64) False

(‘h’, 128) False

(‘i’, 256) False

(‘j’, 512) False

(‘k’, 1024) False

One genius way of using shift. I like to know more.

Also this isn’t just in Python, but other programming languages support this, especially C & C++