porting C code

Roy Smith roy at panix.com
Thu Jan 13 20:12:37 EST 2005


Lucas Raab <pythongnome at hotmail.com> wrote:
> I am currently in the process of porting some C code into Python and am 
> stuck. I don't claim to be the greatest C/C++ programmer; in fact, my 
> skills at C are rudimentary at best. My question is I have the 
> statement: "typedef   unsigned long int  word32" and later on: "word32 
> b[3]" referencing the third bit of the integer. 

Are you sure that's accessing the third bit?  It looks to me like it's 
accessing index 3 (counting from 0) of an array of ints.

> How do I do the same in Python??

In any case, if you're doing bit-fiddling in Python, you've got two 
basic sets of tools.

First, the basic arithmetic operators.  Boolean and (&), or (|), 
left-shift (<<) and right-shift (>>) operators work in Python just like 
they do in C.  Integer constants starting with 0x are in hex, and the 
"%x" format specifier prints integers in hex.  You can play all the 
normal C bit-operation tricks.  To test bit 7, you can do "word & (0x1 
<< 7)".  To set bit 4, use "word |= (0x1 << 4)".

Second, the struct module 
(http://docs.python.org/lib/module-struct.html) is useful for packing 
and unpacking C structures written out into binary files.



More information about the Python-list mailing list