[Tutor] operators >> and &
Steve Willoughby
steve at alchemy.com
Sat Feb 13 20:32:56 CET 2010
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
steve at alchemy.com | to hunt for Tupperware.
More information about the Tutor
mailing list