Good day, I am working in a 16-bit C environment, and I want to convert a float value into its bit sequence such as an integer value. There are multiple ways I know how to achieve this, one is with a union; such as:
union ConvertFloatToInt
{
float input;
unsigned long output;
};
this will "convert" the floating values into a long value, by reading the same memory area, just interpreting it differently.
union ConvertFloatToInt x;
x.input = 20.00;
result
x.output = 0x41A00000;
Other methods are void pointer casts...
float input = 40.00;
unsigned long output;
void* ptr;
ptr = &input;
output = *(unsigned long*) ptr;
result
output = 0x42200000;
This is the idea of what I am trying to do, however, I want the compiler to do the conversion for me, during build, not during run time.
I need a to insert the converted floating data into a constant (const) unsigned long.
I was thinking of trying to convert the float value into a void, and then the void into the unsigned long. Something like this: (and yes this is incorrect, you can not cast to a void)
const unsigned long FloatValue = (unsigned long) ((void) ((float) 20.654));
Is there some way to do this? I was thinking maybe something with void pointers, but all void pointers I know of needs a variable, and variables may not be used in the assignment of const values.
Edit
I am using a C90 compiler. The question is intended in the file scope.
Conclusion
The conclusion was that there is no real solution to this question except when working in the block scope. For which multiple answers were given, and I thank all of you.
My Solution
This is not a good solution, however it solves my problem, but I do not think that this will help many people either. I created a small program for a demonstration purpose. This is not my projects code, and also not the compiler used in my project (before someone says that this is not a C90 compiler)
The compiler used in the demonstration: gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
typedef union
{
float myfloat;
unsigned long mylong;
} custom_type;
typedef struct
{
int a;
int b;
custom_type typeA;
custom_type typeB;
} my_struct;
const my_struct myobj =
{
1,2,3.84F,4
};
int main(void)
{
printf(":: %f\n", myobj.typeA.myfloat);
printf(":: %ul\n", myobj.typeA.mylong);
return 0;
}
Output
:: 3.840000
:: 1081459343l
This is little bit crude, however it works in the file scope (but generates warnings).