Hello,
how can I achieve
long l = WHAT_EVER_MACRO (-12.5); main() { printf("%X",l); }
resulting in output "0xC1480000" the binary representation of the float -12.5 . Without that MACRO the value is 0xFFFFFFF4 = -12 for integers .
Because of given circumstances in an existing project I have to store float values during initialization in long variables.
Is there any possibility?
Thanks in advance
Jürgen
As I did write earlier, the floats will not take their binary representation until (not before) they are stored in memory.
If the value is already available in a variable, it's possible to use a type cast of a pointer to that variable. The other option is to assign the value to a union and later read out the value using one of the other data elements sharing the union.
The next alternative is to move all such floating point constants into a separate header file with named constants that you preprocess into their binary representation.
Now I got you!
I tryed
float f32ConstInitval = -12.5; uint32_t ui32Testvalue = (*(uint32_t *)&f32ConstInitval);
and got: 'scalar': initializer is not a constant :-(
With
static const float f32ConstInitval = -12.5; uint32_t ui32Testvalue = f32ConstInitval);
I got ui32Testvalue = 0xFFFFFFF4 as I asked my debugger :-(
but with
static const float f32ConstInitval = -12.5; uint32_t ui32Testvalue = (*(uint32_t *)&f32ConstInitval);
I yielded my desired ui32Testvalue = 0xC1480000 :-D with a litte overhead of 4 Bytes in far flash.
Thanks a lot
or to make a pointer (void or unsigned long) and points it to the floater.
We use this construction since several years for different integer data types (8, 16, 32 bits signed and unsigned) but now it is the first time to use a float variable.
And that's your problem right there. That construction is wrong, and has been for all those years. It relies on the incorrect assumption that you can stuff whatever data you have into a 32-bit integer and recover it unharmed later. The right way of doing that would been to use a union all along, or simply a buffer of bytes.
Therefor my question for a computing macro or a compiler directive not to convert the float to an integer.
No such construction can possibly yield a compile-time constant, which is what you would need for initializing a static variable.