4 ms·
I find it interesting that in the past float -> int was exposed the same way unsigned int -> int was exposed. With a C-style cast you don't think that a conver
by WirelessGigabit 3y ago
I find it interesting that in the past float -> int was exposed the same way unsigned int -> int was exposed.
With a C-style cast you don't think that a conversion is happening. You think it's just re-interpreting the bits.
But that's not the case with floats -> int. You can't just look at a float with int-colored glasses.
- grishka 3y agoIf you really want to reinterpret an int as a float, you need pointers: float floatValue = *(float*)&intValue;
- OhMeadhbh 3y agoYou probably want to look at sizeof( float ) and sizeof( int ). My guess is they'll be different, so do something like: #include <stdio.h> #include <stdint.h> int main() { uint32_t i = 1200053440 + 64; float * fp = (float *) &i; float f = *fp; printf( "%ld %ld %ld\n", sizeof( i ), sizeof( fp ), sizeof( f ) ); printf( "%08X %d %f\n", i, i, f ); return( 0 ); } But I'm nitpicking. Your intent was clear from the much smaller example you gave.
- OhMeadhbh 3y agoHunh. I just discovered that when you cast the 32 bit 2's complement -273613110 as an IEEE 754-2008 binary32 float, you get -109554765609536775148540002304.0 which, when you look at it's in-memory representation as a series of octets on a little-endian machine, it's CAFEBOEF. How to get to DEADBEEF is left as an exercise for the reader. The next time I need a floating point constant, I'm picking -109554765609536775148540002304.0.
- gpderetta 3y agoon most (but of course not all) machines a float is an IEEE 32 bit float and an int is also a 32 bit integer.
- lifthrasiir 3y agoIt's an undefined behavior. Use an union: union { float f; int i; } value; value.i = intValue; float floatValue = value.f;
- OhMeadhbh 3y agoOnly in C++. In C, it's Unspecified.
- lifthrasiir 3y agoEven in C, incompatible object accesses are undefined, not unspecified. (`char` is a major exception.) Using `union` is explicitly allowed by ISO C for this use case; you need to use `memcpy` or `std::bit_cast` in C++ instead though.
- gpderetta 3y agoInt->int can sign extend. That's also not just reinterpreting the bits.
- WirelessGigabit 3y agoI understand that happens when you go to a different size. But I haven't seen this when going from signed int -> unsigned int or vice versa.