Quantcast
Channel: Linux by Examples » python
Viewing all articles
Browse latest Browse all 10

Bit shifting can be done in python just like in c

$
0
0

It was amazing to discover that I can do bit shifting in python just like in c, the syntax makes no different at all. Let us look at how easy I can do a bit shifting. I write an example loop by shifting the bit leftwards.


for i in range(0,10):
    print "0x0001 << %d = 0x%04X" % ( i , 0x1 << i)

The result is


0x0001 << 0 = 0x0001
0x0001 << 1 = 0x0002
0x0001 << 2 = 0x0004
0x0001 << 3 = 0x0008
0x0001 << 4 = 0x0010
0x0001 << 5 = 0x0020
0x0001 << 6 = 0x0040
0x0001 << 7 = 0x0080
0x0001 << 8 = 0x0100
0x0001 << 9 = 0x0200

The important part in the example is this :

0x1 << i

Let say I wanna shift the bits of a value rightwards 3 times, I will do this:

value = 102
print value >> 3

The result will be 12.

To know more about what is bit shifting, check out wikipedia.

Have Fun!


Viewing all articles
Browse latest Browse all 10

Trending Articles