Bit shifting can be done in python just like in c

April 1st, 2009 mysurface Posted in Developer, python | Hits: 220778 | 4 Comments »

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!

4 Responses to “Bit shifting can be done in python just like in c”

  1. I visit your website frequently and its very good , I am not a expert webmaster but i like your blog as its very simple and understandable.. please keep it up , 10/10 marks…

  2. you can try this in python:
    ,you will get 33554432000L.
    but in c# or C++,this will be:
    only 1000L << 25 = 33554432000 in c.

  3. Your post is an inspiration for me to study more about this subject. I must confess your clarity broadened my views and I will right away grab your rss feed to remain up to date on any succeeding articles you might write. You are due, thanks for a job well done!

  4. simple explanantion how to use bitsfit in python. thank for your post

Leave a Reply