Pythonic bit twiddling

Bengt Richter bokr at oz.net
Fri Feb 22 02:03:17 EST 2002


On Thu, 21 Feb 2002 17:59:14 -0800, Jim Richardson <warlock at eskimo.com> wrote:

>
>Pythonic bit shuffling question
>
>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. 
>
Unless you are mixing in other data somehow into the byte, there is only
256 possible states of your input and output, so you should able to
pre-construct a translation table and say
    outByte = transTable[inByte]

and be done. This may not be smaller than defining a function
to do it, but if you need speed, it ought to run faster.
If your in and out bytes are characters, the above transTable
becomes a string and you have
    outByte = transTable[ord(inByte)]

It sounds like you should be able to describe your function in detail
pretty easily. Why not post a cut at a function definition?

Then you can decide to use it directly or use it to compute a
translation string, per your priorities. If you are doing exactly
the same thing to both nybbles, you can do a 16-item lookup for
that part. It might be easier to enumerate than to program
the logic, depending.

Regards,
Bengt Richter




More information about the Python-list mailing list