signed to unsigned

Chris Rebert clp2 at
Fri Feb 17 20:05:23 CET 2012

On Fri, Feb 17, 2012 at 10:51 AM, Brad Tilley <kj4eit at> wrote:
> In C or C++, I can do this for integer conversion:
> unsigned int j = -327681234; // Notice this is signed.
> j will equal 3967286062. I thought with Python that I could use struct
> to pack the signed int as an unsigned int, but that fails:
>>>> x = struct.pack("<I", -327681234)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> struct.error: integer out of range for 'I' format code
> Is there an easy way in Python to do the same conversion that C or C++
> code does? Thanks for any advice.

Pack it as the actual type, then unpack it as the desired type:

Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import pack, unpack
>>> unpack('=I', pack('=i',-327681234))

I would think there's some more efficient way to do this though.


More information about the Python-list mailing list