Bit Operations

Tim Chase python.list at tim.thechases.com
Wed Nov 28 15:20:28 EST 2007


> I'm really confused on how t do it, maybe cause python is
> type-less (dynamic typed)

Being duck-typed doesn't really have anything to do with it. 
Python supports logical shifting and combining

> i've a byte that naturally is composed from 2 nibbles hi&low,
> and two chars.. like A nd B. What i wonna do is to write A to
> the High nibble and B to the the lower nibble. Or an other
> example can be i've 2 numbers.. like 7 and 8 and whant to do
> the same as for chars.

 >>> a = int('1001', 2)
 >>> b = int('0110', 2)
 >>> a
9
 >>> b
6
 >>> 0xff & (((0xff & a) << 4) | (0xff & b))
150

or, if you're sloppy,

 >>> (a << 4) | b
150

And for verification:

 >>> int('10010110', 2)
150

Thus, that can be wrapped up as a function

 >>> nibbles2byte = lambda a,b: \
   0xff & (((0xff & a) << 4) | (0xff & b))
 >>> nibbles2byte(a,b)
150


-tkc







More information about the Python-list mailing list