bitshit in Python

Thomas Wouters thomas at xs4all.net
Sat May 26 10:02:16 EDT 2001


On Sat, May 26, 2001 at 03:27:23PM +0200, Gorny wrote:

> I've got the following code in C and it works perfect.. :)

Python isn't C. The code snippet you posted doesn't make sense in Python
because it doesn't have structs like C has them, and it doesn't have the
concept of an unsigned datatype, let alone one that fits in half a byte :) A
single Python Int type is a C int, a C long and a C pointer in size, not
counting the size of the type object (which all python ints share)

If you just want to be able to split a char into two numbers, you can do
something like:

def encode(one, two):
    if one > 8 or two > 8:
        raise ValueError, "arguments too large to convert"
    return chr((two << 4) | one)


def decode(char):
    return ord(char) & 0xF, (ord(char) >> 4) & 0xF    

If you're just interested in storing something as 'efficiently' as possible,
combine the above with the 'struct' module.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list