[Tutor] operators >> and &

Alan Gauld alan.gauld at btinternet.com
Sun Feb 14 00:54:24 CET 2010


"David Abbott" <david at pythontoo.com> wrote 
> I am attempting to understand this little program that converts a
> network byte order 32-bit integer to a dotted quad ip address.


> def int2ip(l):
>    if MAX_IP < l < 0:
>        raise TypeError, "expected int between 0 and %d inclusive" %
> MAX_IP
>    return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l &
> 255)

The >>> shifts the number bitwise to the right. 
Thus the number 8 is 1000 in binary

8 >> 3 -> 0001

So taking a 32 bit number and shifting it right 24 bits leaves the 
top 8 bits

N & 255 uses a bitwise and to filter the number N by removing 
anything outside the 8 bits (should any spurious 1's sneak in...)
In bitwise and a 1 and 1 gives 1 any other combination gives 0.
So and'ing with 255 (11111111)  simply repeats the 8 bits of N 
while zeroing all the other bits.

Similarly >> 16 gets the top 16 bits and andintg with 255 
processes bits 16-24 and zeros the rest.

And so on for the other two groups of 8 bits.

There is more on using bitwise operators and "masking" in my 
Using the OS topic in my tutorial(v2). (Look for a "sidebar" half 
way down)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list