-1

I want to reinterpret 4 bytes as IEEE 754 single-precision binary in C.

To obtain the bytes that represent float, I used:

num = *(uint32_t*)&MyFloatNumber;
aux[0] = num  & 0xFF;
aux[1] = (num >> 8) & 0xFF;
aux[2] = (num >> 16)  & 0xFF;
aux[3] = (num >> 24)  & 0xFF;
  • num is a uint32_t.
  • aux[] is int[4].

To reinterpret the bytes as a float, I’m trying:

Buff = *(float*)&aux;

In that second case nothing apears on "Buff"

  • Buff is a float.

What am I doing wrong in the second case?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Guilherme
  • 35
  • 1
  • 8

1 Answers1

3

2 problems:

  1. Buff = *(float*)&aux; attempts to use the address of an array of 4 int as a pointer to a float. aux[] is perhaps 16 bytes long and a IEEE 754 single-precision binary float is expected to be 4 bytes.

  2. Both casts: (uint32_t*) and (float*) invoke undefined behavior as well as alignment and anti-aliasing issues. Better to use a union.

    int main(void) {
      union {
        float f;
        unsigned char uc[sizeof(float)];
      } x;
    
      // float to bytes
      x.f = 1.23f;
      printf("%x %x %x %x\n", x.uc[0], x.uc[1], x.uc[2], x.uc[3]);
    
      // bytes to float
      x.uc[0] = 0xA4;
      x.uc[1] = 0x70;
      x.uc[2] = 0x9D;
      x.uc[3] = 0x3F;
      printf("%.8e\n", x.f);
    }
    

Output

a4 70 9d 3f
1.23000002e+00
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • I'm using a microcontroller that does not allow the use of the printf function, you would have another way to do the conversion (bytes to float)? – Guilherme Jan 09 '18 at 00:07
  • @Guilherme Even without `printf("%.8e\n", x.f);`, the converted `float` is in `x.f`. `printf("%.8e\n", x.f);` is only for display purposes. – chux - Reinstate Monica Jan 09 '18 at 01:56