I need to write an IEEE single-precision floating point number to a 32-bit hardware register at a particular address. To do that, I need to convert a variable of type float to an unsigned integer. I can get the integer representation like this:
float a = 2.39;
unsigned int *target;
printf("a = %f\n",a);
target = &a;
printf("target = %08X\n",*target);
which returns:
a = 2.390000
target = 4018F5C3
All good. However this causes a compiler warning "cast.c:12: warning: assignment from incompatible pointer type"
Is there any other way to do this which doesn't generate the warning? This is for specific hardware, I don't need to handle different endianness etc and I don't want to loop through each char for performance reasons as some other questions tend to suggest. It seems like you might be able to use reinterpret_cast in C++ but I am using C.
You can use type punning with a union,
union {
float f;
uint32_t u;
} un;
un.f = your_float;
uint32_t target = un.u;
to get the bits. Or you can use memcpy
.