3

I found a way to convert a float to binary in c through this answer: Convert float to binary in C, but I'm not sure what the code used in the answer *((int*)&f) actually does to convert the number. What does it do exactly?

Pahasa
  • 35
  • 5
  • 3
    It takes the address (`float *`), casts to `int *`, and dereferences. But see https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule - use `memcpy` instead! – o11c Sep 29 '19 at 00:40

1 Answers1

7

It invokes undefined behavior, meaning your program is invalid if it's reachable.

What someone intended for it to do is to reinterpret the bits of a float as an int, assuming int is 32-bit and probably also that float is IEEE single.

There are two correct ways to do this (int replaced with uint32_t to remove the first useless assumption):

  1. (union { float f; uint32_t i; }){f}.i
  2. uint32_t i; memcpy(&i,&f,sizeof i);
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Side note: the purpose of re-interpreting the bits of a float is generally to access underlying (implementation defined) internal representation of a float, typically sign bit, biased exponent, and significand bits... Sun fdlibm mathematical library use those bits extensively (for double precision). – aka.nice Sep 30 '19 at 17:10
  • @R.. So if I'm understanding 2 correctly, `memcpy` just copies the address of `f` and makes it the address of `i` as well, and since `i` is a `uint32_t` the bits are reinterpreted as that type? If it is, was IEEE-754 built with this application in mind or is this something that was discovered at a later date? – Pahasa Oct 01 '19 at 17:54