I have the following data.
float u[4] = {0x3f951d32, 0x3f207887, 0x3d99c3a0, 0x3eb405d2};
ScaleFunction(u);
void ScaleFunction(float *u_ptr)
{
for(int i = 0; i < 4; i++)
{
printf("u[%d] = %f\n", u_ptr[i]);
}
// And a lot more
}
The application containing the snippet above is executed on a 64 bit machine running ubuntu 16.10.
Much to my chagrin, the floating point numbers are incorrectly interpreted as: 1066736960.000000, 1059092608.000000, 1033487232.000000 and 1051985344.000000.
The numbers when printed in hexadecimal confirm that the caller passes the correct values to callee.
What am I doing wrong here?
I even tried the following with no joy.
uint32_t u[4] = {0x3f951d32, 0x3f207887, 0x3d99c3a0, 0x3eb405d2};
ScaleFunction(u);
void ScaleFunction(uint32_t *u_ptr)
{
float ut[4];
for(int i = 0; i < 4; i++)
{
ut[i] = (float) u_ptr[i];
printf("ut[%d] = %f\n", ut[i]);
}
// And a lot more
}
I expect to interpret the hexadecimals in the callee as: 1.1649, 0.6268, 0.075, 0.5516
The problem is, that you initialize your array with large integer values, not the hex representation of the floats. With your hex constants starting with values around 0x3f it's pretty clear that these are floating point data with values around 1.0.
As far as I know there is no direct way to initialize a float array with hex constants (if there is one, community, please tell me!).
So you have to define your data-array as int and convert it to float as you use it. IMPORTANT: Directly casting the pointer from int to float will break the aliasing rule of C and may result in code that looks correct but misbehaves.
Converting between the two data-types via memcpy is safe though and the compiler is usually smart enough to spot this and optimize it out.
So this solution here does what you want:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
uint32_t u[4] = {0x3f951d32, 0x3f207887, 0x3d99c3a0, 0x3eb405d2};
void ScaleFunction(uint32_t *u_ptr)
{
for(int i = 0; i < 4; i++)
{
float temp;
memcpy (&temp, &u[i], sizeof (float));
printf("u[%d] = %f\n", i, temp);
}
// And a lot more
}
void main (int argc, char **args)
{
ScaleFunction (u);
}