4 ms·
If you really want to reinterpret an int as a float, you need pointers: float floatValue = *(float*)&intValue;
by grishka 3y ago
If 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.