0

I'm having a python code that uses the number 2637268776 (bigger than sys.maxint in 32-bit systems). Therefore it is saved as a long type.

I'm using a C++ framework bindings in my code, so I have a case where it's being converted into int32, resulting in an int32 overflow:

2637268776 --> -1657698520

In my case, it can happen only one time, so it's safe to assume that if the integer is negative, we had a single int overflow. How can I mathematically reverse the numbers?

iTayb
  • 12,373
  • 24
  • 81
  • 135
  • 1
    What do you mean by "mathematically reverse"? – Klas Lindbäck Mar 26 '13 at 12:00
  • Can't you just use an unsigned 32bit integer? – aufziehvogel Mar 26 '13 at 12:03
  • The number you're showing can still be stored as an unsigned 32bit int. Now it depends on whether this holds for all numbers that you're using, or you need more than unsigned int can hold. I suppose this is difficult to guarantee, so you should try to use long int in the c++ side of the code or you'll run into the ambiguities NPE showed in his answer. – Piotr99 Mar 26 '13 at 12:09

2 Answers2

5

In short, you can't. There are many long integers that would map to the same negative number. In your example, these are 2637268776L, 6932236072L, 11227203368L, 15522170664L, 19817137960L etc.

Also, it is possible to get a positive number as a result of such an overflow. For example, 4294967297L would map to 1.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

You could add 2 * (sys.maxint + 1) to it:

>>> -1657698520 + (2 * (sys.maxint + 1))
2637268776L

but that only works for original values < 2 * (sys.maxint + 1), as beyond that the overflow will run into positive numbers, or worse, overflow again.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343