Bit Operations

Tim Chase python.list at tim.thechases.com
Wed Nov 28 16:49:40 EST 2007


>>  >>> 0xff & (((0xff & a) << 4) | (0xff & b))
>> 150
>>
>> or, if you're sloppy,
>>
>>  >>> (a << 4) | b
>> 150
> 
> Slightly OT, maybe - why exactly is the second alternative 'sloppy?'
> I believe you, because I had a problem once (in Java) with bytes not
> having the value I expected unless I did the and-magic, but I wasn't
> clear on why.  Is it an issue with the word otherwise possibly not
> being zeroed out?

Whoops...extra "f"s slipped into my nibble-mask

"Sloppy" lets through things like

 >>> a = int('11111', 2) # overflows a nibble
 >>> b = int('11111', 2)
 >>> (a<<4) | b
511
 >>> 0xff & (((0xf & a) << 4) | (0xf & b))
255

It clamps each nibble to a true nibble, and the output to a true 
byte.  If you validate your nibbles, you could be lazy yet 
accurate with

 >>> result = ((0xf & a) << 4) | (0xf & b)
 >>> result
255

To get the nibbles back out of the resulting byte, one can simply

 >>> a = 0xf & (result >> 4)
 >>> b = result & 0xf

-tkc







More information about the Python-list mailing list