Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a = -2147483648 - a; compiler optimization

I'm trying to learn how to reverse engineer software and all the tricks to understand how the code looks like before the compiler optimizations.

I found something like this several times:

    if (a < 0)
      a = -2147483648 - a;

I originally thought it was an abs(): a underflows so you get the positive value. But since a is negative (see the if), this is equivalent to:

    if (a < 0)
      a = -2147483648 + abs(a);

Which will be a very small negative number, and not the absolute value of a at all. What am I missing?

like image 984
Thomas Bonini Avatar asked Aug 16 '10 20:08

Thomas Bonini


2 Answers

It is converting the number so that bit 31 becomes a sign bit, and the rest bits (0...30) denotes the absolute magnitude. e.g. if a = -5, then after the operation it becomes 0x80000005.

like image 107
kennytm Avatar answered Sep 30 '22 14:09

kennytm


It appears to be converting from 2's complement to sign-magnitude

like image 20
BlueRaja - Danny Pflughoeft Avatar answered Sep 30 '22 13:09

BlueRaja - Danny Pflughoeft