Reading Brut float data from Memory

Hi,
I need to do a resumé on Gentleman's algorithm and was wondering if there was a way to print a float as it actually is in memory (The Binary).

Maybe pointing a bool to the first adress then doing bool++?

Thanks in advance.
Use a union to cast the float to integer values:
1
2
3
4
typedef union {
  float f;
  unsigned char b[ sizeof( float ) ];
  } t_float_to_bits;

You can then decode the array of bytes into bits.
1
2
3
4
5
6
  t_float_to_bits f2b;
  f2b.f = 12.3;
  for (int i = 0; i < sizeof( f2b.b ); i++)    // Assumes little-endian (PC)
    for (int j = 0; j < 8; j++)
      cout << ((f2b.b[ i ] >> j) & 1) ? '1' : '0';
  cout << endl;


One thing to keep in mind is the endianness of your processor. x86 processors store least significant bytes first, most significant bytes last. So

0xABCD (two bytes)

would be stored as

CD AB (lsb stored first)

A Sparc processor, in change, stores most significant bytes first. So the example would be

AB CD (msb stored first)


There are a few processors that really goober around with the order, but I don't think it likely you are using one of them...

Hope this helps.
Last edited on
Topic archived. No new replies allowed.