Reverse Engineering for Beginners

(avery) #1

CHAPTER 19. MANIPULATING SPECIFIC BIT(S) 3031 2322 0 CHAPTER 19. MANIPULATING SPECIFIC BIT(S)


S exponent mantissa or fraction

( S—sign)

The sign of number is in theMSB^6. Will it be possible to change the sign of a floating point number without any FPU
instructions?


#include <stdio.h>


float my_abs (float i)
{
unsigned int tmp=((unsigned int)&i) & 0x7FFFFFFF;
return (float)&tmp;
};


float set_sign (float i)
{
unsigned int tmp=((unsigned int)&i) | 0x80000000;
return (float)&tmp;
};


float negate (float i)
{
unsigned int tmp=((unsigned int)&i) ^ 0x80000000;
return (float)&tmp;
};


int main()
{
printf ("my_abs():\n");
printf ("%f\n", my_abs (123.456));
printf ("%f\n", my_abs (-456.123));
printf ("set_sign():\n");
printf ("%f\n", set_sign (123.456));
printf ("%f\n", set_sign (-456.123));
printf ("negate():\n");
printf ("%f\n", negate (123.456));
printf ("%f\n", negate (-456.123));
};


We need this trickery in C/C++ to copy to/fromfloatvalue without actual conversion. So there are three functions: my_abs()
resetsMSB; set_sign() setsMSBand negate() flips it.


19.4.1 A word about theXORoperation.


XORis widely used when one needs just to flip specific bit(s).


Indeed, theXORoperation applied with 1 effectively inverts a bit:


input A input B output
0 0 0
0 1 1
1 0 1
1 1 0

And vice-versa, theXORoperation applied with 0 does nothing, i.e., it’s an idle operation.


This is a very important property of theXORoperation and it’s highly recommended to memorize it.


19.4.2 x86


The code is pretty straightforward:


Listing 19.21: Optimizing MSVC 2012

_tmp$ = 8
_i$ = 8


(^6) Most significant bit/byte

Free download pdf