views:

238

answers:

4

Hello, 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?

A: 

Maybe: http://en.wikipedia.org/wiki/Two%27s_complement ?

Mchl
+6  A: 

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.

KennyTM
In other words it's a conversion from two's complement to sign magnitude. (I wonder where that's useful in a typical compiler.)
Gilles
@Gilles: it may be the actual application code and not an optimization from the compiler. I just assumed it was an optimization because it looked like one.
Andreas Bonini
Any suggestion why the reverse engineered software would be doing this often enough for the OP to notice it in particular? I was thinking about the possibility that this was part of a software conversion from int to IEEE 754 floating-point representation, but it seems to me that it would always be simpler to position the sign bit last in these cases.
Pascal Cuoq
For integers which can be represented in this way having a number in this format would be very useful for printing out signed integers or getting ready to do multiplication or division on machines that can't do signed versions of those operations natively.
nategoose
@Pascal: I don't know. We need more context from @Andreas.
KennyTM
The part of the code I was looking at was a patching algorithm that uses a modified BSDIFF algorithm. I was trying to figure out the kind of modifications they did to that algorithm.
Andreas Bonini
+4  A: 

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

BlueRaja - Danny Pflughoeft
A: 

I sincerely hope that the original source said 0x80000000 and not -2147483648 ! The hex number at least gives the reader a clue. The decimal is very cryptic.

Jay
Being it decompiled code, I have no way to know what the original source says. Also, this should be a comment.
Andreas Bonini
That's why I said "I hope the original source ..." I presumed if you're decompiling that you don't have the original source.
Jay