[Tutor] operators >> and &

spir denis.spir at free.fr
Sun Feb 14 14:42:05 CET 2010


Just reviewed this post and wonder whether the explanation is clear for anyone else as myself ;-)

Denis

On Sat, 13 Feb 2010 23:17:27 +0100
spir <denis.spir at free.fr> wrote:

> On Sat, 13 Feb 2010 13:58:34 -0500
> 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.
> > 
> > #!/usr/bin/python
> > # Filename : int2ip.py
> > 
> > MAX_IP = 0xffffffffL
> > ip = 2130706433
> > 
> > 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)
> > 
> > result = int2ip(ip)
> > print result
> > 
> > I don't understand the l>>24 & 255. 
> > 
> > from the docs;
> > Right Shift a >> b rshift(a, b)
> > Bitwise And a & b and_(a, b)
> > 
> > thanks
> > 
> 
> In addition to Steve's excellent explanation:
> Shifting to the left n bits is equivalent to multiplying by 2^n. Shifting to the right n bits is equivalent to dividing by 2^n. Shifting to the right 8 bits is thus equivalent to dividing by 2^8=256; which means making each octet (in a long integer) one level less significant.
> AND-ing is equivalent to masking (this is actually called a mask operating) all bits wich are not 1 in the mask. So AND-ing with 11111111=255 masks all bits except the ones of the least significant octet.
> If you represent a 32-bit integer as 4 octets, or 8 hex digits, the picture is easier to catch:
> n = 0x12345678		# 0x12345678 = abcd (b=0x34=52)
> # to get b:
> temp = n >> 16		# 0x00001234 = 00ab
> b = temp & 255		# 0x00000034 = 000b
> 
> You can perform the same operation without bit-level operators, using modulo and integer division. To understand this, again consider the "abcd" representation: this means a 32-bit integer can be seen as 4-digit number written in base 256 (yes!). Division by 256^n gets rid of n lowest digits, moving down all other ones. Modulo 256^n gets rid of digits in higher position than n. (This may help and fully catch the sense of "base n").
> n = 0x12345678		# 0x12345678 = abcd (b=0x34)
> # to get b:
> temp = n // (256**2)	# 0x00001234 = 00ab
> b = temp % 256		# 0x00000034 = 000b
> 
> (examples untested)
> Bit operations are by far faster, indeed. 
> 
> 
> Denis

________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list