I have this bit of code that is outputting the wrong results.
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char bytes[4];
float flt=0;
bytes[0]=0xde;
bytes[1]=0xad;
bytes[2]=0xbe;
bytes[3]=0xef;
memcpy( &flt, bytes, 4);
printf("bytes 0x%x float %e\n", flt, flt);
return 0;
}
the output that I get is
bytes 0xc0000000 float -2.000001e+00
I am expecting to get
bytes 0xdeadbeef float -6.2598534e+18
edit #1
as was pointed out the endianness could be different which would result in the following
bytes 0xefbeadde float -1.1802469e+29
what I don’t understand is the cast from float to unsigned int resulting in 0xc0000000 (the float in the same printf statement being -2.0000 I would attribute to compiler optimization)
this was working before on a different computer. It could be an architecture change.
It is not problem of memcpy.
floatis allways converted todoublewhen passed over...of printf, so you just can’t get 4 bytes on most of intel architectures.0xdeadbeefin this code, you assume that your architecture is BIG endian. There are many little endian architectures, for example Intel x86.