Make your own free website on Tripod.com
 
« February 2007 »
S M T W T F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
You are not logged in. Log in

Programming Tips
Tuesday, 6 February 2007
Extracting bytes in a floating point variable
Mood:  crushed out
Topic: VC++

The easiest way to get the bytes in a floating point variable...

BYTE byFloatBytes[sizeof( float )] = { 0 };
float fFloatNumber = 0.191911f;
memcpy( &byFloatBytes, &fFloatNumber, sizeof( byFloatBytes ));

or

BYTE byDoubleBytes[sizeof( double )] = { 0 };
double dDoubleNumber = 0.191911;
memcpy( &byDoubleBytes, &dDoubleNumber, sizeof( byDoubleBytes ));

or

float fFloatVar = 21343.34f;
LPBYTE lpFloatBytes = reinterpret_cast< LPBYTE >( &fFloatVar );

// Now lpFloatBytes can be accessed as an array likewise
lpFloatBytes[0]
lpFloatBytes[1]
lpFloatBytes[2]
lpFloatBytes[3]

or

// Use a union
union
{
      double dDoubleVar;
      BYTE byBytes[sizeof( double )];
}AUnion;

AUnion.dDoubleVar = 234234.233123;

// Now AUnion byBytes should be holding the double value in bytes
AUnion.byBytes[0], AUnion.byBytes[1], AUnion.byBytes[2],AUnion.byBytes[3]...

etc.

Be sure that you don't step out of the size of the floating point variable which could lead to disaster. The first two methods are safe, the second last one should be only used if you are absolutely confident as to what you are doing.


Posted by Nibu babu thomas at 5:14 PM
Updated: Monday, 26 February 2007 5:32 PM

View Latest Entries