Link to home
Start Free TrialLog in
Avatar of Surfer
Surfer

asked on

Float conversion to 4 bytes?

I need to comvert 1 float into 4 bytes and then back to 1 float again.  Someone told me to try this:
FLOAT f1 = 123.456, f2 = 0.0 ;
BYTE byByte1 = HIBYTE( HIWORD( f1 ) ) ;
BYTE byByte2 = LOBYTE( HIWORD( f1 ) ) ;
BYTE byByte3 = HIBYTE( LOWORD( f1 ) ) ;
BYTE byByte4 = LOBYTE( LOWORD( f1 ) ) ;
//rebuild
f2  = byByte1 << 24 | byByte2 << 16 | byByte3 << 8 | byByte4 ;

The rebuild answer for this is f2 = 123.000 and not 123.456.  How can a get the rest of my float?  What am I doing wrong? Also what is required to break down to bytes, a double (8bytes) and rebuild the 8 bytes into one double? All sugestions welcome and sample code is greatly appreciated!  
Avatar of Surfer
Surfer

ASKER

Edited text of question
I don't understand what you want to do.
variable (as you probably know) of type float takes 4 bytes in memory. So if you need access to each byte of them:

BYTE *p = (BYTE*)&f1;
p[0] - first byte and so on.

the code in your question doesn't work because bit operation OR can't return float type.

may be something like this
      FLOAT f1 = 123.456, *f2;
      int *pf, i2;
      f2 = new FLOAT;
      pf = (int*)&f1;
      BYTE byByte1 = HIBYTE( HIWORD( *pf ) ) ;
      BYTE byByte2 = LOBYTE( HIWORD( *pf ) ) ;
      BYTE byByte3 = HIBYTE( LOWORD( *pf ) ) ;
      BYTE byByte4 = LOBYTE( LOWORD( *pf ) ) ;
      //rebuild
      i2  = byByte1 << 24 | byByte2 << 16 | byByte3 << 8 | byByte4;
      memcpy((void*)f2, (void*)&i2, 4);

Avatar of Surfer

ASKER

I tried to modify your code sample that works with type float to work with type double and it dose not work.  All suggestions welcome.

double r1 = 123.456, *r2 ;
r2 = new double ;
_int64 i2 ;

BYTE *pr = (BYTE*)&r1 ;

BYTE byByte1 = pr[7] ;
BYTE byByte2 = pr[6] ;
BYTE byByte3 = pr[5] ;
BYTE byByte4 = pr[4] ;
BYTE byByte5 = pr[3] ;
BYTE byByte6 = pr[2] ;
BYTE byByte7 = pr[1] ;
BYTE byByte8 = pr[0] ;

i2 = byByte1 << 56 | byByte2 << 48 | byByte3 << 40 | byByte4  << 32 | byByte5 << 24 | byByte6 << 16 | byByte7 << 8  | byByte8 ;

memcpy((void*)r2,(void*)&i2,8) ;            

delete r2 ;
Your problem is due to the way floats are stored internally - IEEE format.
ASKER CERTIFIED SOLUTION
Avatar of scrapdog
scrapdog
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial