Long:
char long_num[8];
for(i=0; i<8; i++)
long_num[i] = data[pos++];
memcpy(&res, long_num, 8);
The values in the long_num are as follows:
127 -1 -1 -1 -1 -1 -1 -1
res should be the maximum value of signed long, but is -129 instead.
EDIT: This one is taken care of. It was a result of communication problems: For the person providing data, a long is eight bytes; for my C it’s four.
Float:
float *res;
/* ... */
char float_num[4];
for(i=0; i<4; i++)
float_num[i] = data[pos++];
res = (float *)float_num;
It’s zero. Array values:
62 -1 24 50
I also tried memcpy(), but it yields zero as well. What am I doing wrong?
My system: Linux 2.6.31-16-generic i686 GNU/Linux
These are two questions, quite unrelated.
In the first one, your computer is little-endian. The sign bit is set in the
longthat you piece together so the result is negative. It is close to zero because many “most significant bits” are set.In the second example, the non-respect of strict aliasing rules could be an explanation for weird behavior. I am not sure. If you are using gcc, try using an union instead, gcc guarantees what happens when you convert data this way using an union.