What’s a proper way of type-punning a float to an int and vice-versa?

Forget casts. Use memcpy. float xhalf = 0.5f*x; uint32_t i; assert(sizeof(x) == sizeof(i)); std::memcpy(&i, &x, sizeof(i)); i = 0x5f375a86 – (i>>1); std::memcpy(&x, &i, sizeof(i)); x = x*(1.5f – xhalf*x*x); return x; The original code tries to initialize the int32_t by first accessing the float object through an int32_t pointer, which is where the rules are … Read more