Pythonic bit twiddling
Jim Richardson
warlock at eskimo.com
Fri Feb 22 03:12:33 EST 2002
On 22 Feb 2002 07:03:17 GMT,
Bengt Richter <bokr at oz.net> wrote:
> 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
>
Thanks, this isn't a bad idea (I am not really python guru, so am easily
overwhelmed sometimes :) I will have to think on it. Speed isn't much of
an issue, as the data is only 9600 and each packet needs a checksum, and
usually, only 8-10 packets a second.
Another reply mentioned a "byte" operator, but I can't find that
anywhere in my python docs. Is it something not in the default setup?
Thanks
--
Jim Richardson
Anarchist, pagan and proud of it
www.eskimo.com/~warlock
Linux, for when you need to get work done, Or you could just play UT...
More information about the Python-list
mailing list