Pythonic bit twiddling

Paul Rubin phr-n2002a at nightsong.com
Thu Feb 21 21:39:26 EST 2002


Jim Richardson <warlock at eskimo.com> writes:
> I have an application that does a calculation on a single byte of data,
> after breaking it into an upper and lower nibble of four bits. How can I
> do this in python? To clarify.
> Take a single byte, break off the upper 4 bits, and do some stuff, then
> do similar stuff with the lower nibble, and then munge them back
> together to create a byte again. This is for a checksum to inteface with
> a bit of embedded stuff. I know how I can do this in C, but as that
> would be the sole bit of copiled code in the app, I'd prefer to avoid
> it if possible. 


Am I missing something?  Python has the usual bit operations that work
on ints.

a = do_some_stuff(byte >> 4)        # upper nibble
b = do_similar_stuff(byte & 0x0f)   # lower nibble
new_byte = (a << 4) + b     # assume a and b are nibble results



More information about the Python-list mailing list