Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20564

Re: signed to unsigned

References <436b024b-20f7-462b-a21e-11f44802e578@s7g2000vby.googlegroups.com>
Date 2012-02-17 11:05 -0800
Subject Re: signed to unsigned
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.5922.1329505526.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Feb 17, 2012 at 10:51 AM, Brad Tilley <kj4eit@gmail.com> 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))
(3967286062,)

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

Cheers,
Chris

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

signed to unsigned Brad Tilley <kj4eit@gmail.com> - 2012-02-17 10:51 -0800
  Re: signed to unsigned Chris Rebert <clp2@rebertia.com> - 2012-02-17 11:05 -0800
    Re: signed to unsigned Brad Tilley <kj4eit@gmail.com> - 2012-02-17 11:10 -0800
  Re: signed to unsigned Peter Otten <__peter__@web.de> - 2012-02-17 20:14 +0100
    Re: signed to unsigned Brad Tilley <kj4eit@gmail.com> - 2012-02-17 11:22 -0800
      Re: signed to unsigned Dave Angel <d@davea.name> - 2012-02-17 14:37 -0500

csiph-web