How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ]

John Machin sjmachin at lexicon.net
Wed Dec 10 22:45:07 EST 2008


On Dec 11, 9:49 am, Explore_Imagination <Mr.HassanShab... at gmail.com>
wrote:
> Hi all
>
> I am new to C and python ... I want to convert C data type uint64
> variable into the Python 32bit Object. I am currently using Python 2.2
> [ It is necessary to use it ]
>
> Kindly give your suggestion how and in which way I can achieve this
> task.

I'm not sure what you mean by "the Python 32bit Object". A Python int
object holds a signed 32-bit integer. A Python long object holds a
signed integer of arbitrary size. You will need to convert your uint64
into a Python long; then, if necessary, check that the result will fit
in an int (result <= sys.maxint).

If the "C variable" is in an 8-byte string that you have read from a
file, the unpack function in the struct module will do the job.
Assuming your computer is little-endian:

>>> maxu64 = '\xff' * 8 # example input string
>>> import struct
>>> result = struct.unpack('<Q', maxu64)[0]
>>> result
18446744073709551615L
>>> 2 ** 64 - 1
18446744073709551615L

If however you mean that in C code you need to build a Python object
to pass over to Python code: According to the Python/C API Reference
Manual (http://www.python.org/doc/2.2.3/api/longObjects.html):

PyObject* PyLong_FromUnsignedLongLong(unsigned long long v)
    Return value: New reference.
    Returns a new PyLongObject object from a C unsigned long long, or
NULL on failure.

If however you mean something else, ....

HTH,
John



More information about the Python-list mailing list