Bit shifting can be done in python just like in c
April 1st, 2009 mysurface Posted in Developer, python | Hits: 188344 | 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!







July 11th, 2009 at 4:43 pm
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…
October 14th, 2009 at 12:40 pm
you can try this in python:
1000<<25
,you will get 33554432000L.
but in c# or C++,this will be:
-805306368
.
only 1000L << 25 = 33554432000 in c.
May 6th, 2011 at 1:40 am
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!
August 22nd, 2011 at 11:59 am
simple explanantion how to use bitsfit in python. thank for your post