On Sat, Feb 13, 2010 at 01:58:34PM -0500, David Abbott wrote:
> I don't understand the l>>24 & 255. 

The >> and << operators (when applied to integers) shift the
bits left or right a number of positions.

The number 5, for example, is 101 in binary, or if you
want to picture that as a 16-bit value, 0000000000000101.

When you do 5 << 3 that takes those bits and shifts them
3 places to the left, so you end up with:
  0000000000101000

The >> works similarly but shifting to the right.

The & operator performs a logical "AND" to the individual
bits of two numbers, where A & B is 1 if A and B are both 1
and 0 otherwise.

People often use them for "masking" out a set of bits
from a bigger value, like this.  To get just the least
significant octet from an IP address like 1.2.3.4, you
would AND it with 255 (0xff) like so:

  ip = 00000001000000100000001100000100   # 1.2.3.4
 0xff= 00000000000000000000000011111111
     & --------------------------------
       00000000000000000000000000000100   # 4

Then you can shift 8 places right and AND again
to get the next octet:

  ip = 00000001000000100000001100000100   # 1.2.3.4

  >>8= 00000000000000010000001000000011   # 0.1.2.3
 0xff= 00000000000000000000000011111111
     & --------------------------------
       00000000000000000000000000000011   # 3

-- 
Steve Willoughby    |  Using billion-dollar satellites
[email protected]   |  to hunt for Tupperware.
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to