23.03.2013 Views

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1.17 Unions<br />

1.17.1 Pseudo-random number genera<strong>to</strong>r example<br />

If we need float random numbers from 0 <strong>to</strong> 1, the most simplest thing is <strong>to</strong> use random numbers genera<strong>to</strong>r<br />

like Mersenne twister producing random 32-bit values in DWORD <strong>for</strong>m, trans<strong>for</strong>m this value <strong>to</strong> float and<br />

then divide it by RAND_MAX (0xffffffff in our case) — value we got will be in 0..1 interval.<br />

But as we know, division operation is almost always very slow. Will it be possible <strong>to</strong> get rid of it, as in<br />

case of division by multiplication? 1.11<br />

Let’s remember what float number consisted of: sign bit, significand bits and exponent bits. We need<br />

just <strong>to</strong> s<strong>to</strong>re random bits <strong>to</strong> significand bits <strong>for</strong> getting float number!<br />

Exponent cannot be zero (number will be denormalized in this case), so we will s<strong>to</strong>re 01111111 <strong>to</strong><br />

exponent — this mean exponent will be 1. Then fill significand with random bits, set sign bit <strong>to</strong> 0 (which<br />

mean positive number) and voilà. Generated numbers will be in 1 <strong>to</strong> 2 interval, so we also should subtract<br />

1 from it.<br />

Very simple linear congruential random numbers genera<strong>to</strong>r is used in my example 61 , producing 32-bit<br />

numbers. The PRNG initializing by current time in UNIX-style.<br />

Then, float type represented as union — that is the C/C++ construction allowing us <strong>to</strong> interpret piece<br />

of memory differently typed. In our case, we are able <strong>to</strong> create a variable of union type and then access <strong>to</strong><br />

it as it’s float or as it’s uint32_t. It can be said, it’s just a hack. A dirty one.<br />

#include <br />

#include <br />

#include <br />

union uint32_t_float<br />

{<br />

uint32_t i;<br />

float f;<br />

};<br />

// from the Numerical Recipes book<br />

const uint32_t RNG_a=1664525;<br />

const uint32_t RNG_c=1013904223;<br />

int main()<br />

{<br />

uint32_t_float tmp;<br />

};<br />

uint32_t RNG_state=time(NULL); // initial seed<br />

<strong>for</strong> (int i=0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!