signed to unsigned

B

Brad Tilley

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:
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.
 
C

Chris Rebert

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:

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.(3967286062,)

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

Cheers,
Chris
 
B

Brad Tilley

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

(3967286062,)

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

Cheers,
Chris


Thanks Chris! I was doing it backwards. I only have a few of these
right now, so performance isn't a concern. I appreciate the advice.

Brad
 
P

Peter Otten

Brad said:
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:

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.
3967286062
 
D

Dave Angel

Very nice! Thanks for that example. Unsigned long longs:

0xffffffffffffffff& -9151314442815602945
9295429630893948671L
Or more generally, use modulo

-13452324 % 2^64
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top