I’m having a problem getting an integer from a char[]. I’s a really simple line of code, but I can’t see where the problem is.
This is the code:
char* rawd = .....
int resultSize = ((int*)rawd)[0];
cout << "BYTES ::: " << (int)(rawd[0]) << " " << (int)(rawd[1]) << " " << (int)(rawd[2]) << " " << (int)(rawd[3]) << endl;
cout << "SIZE RETURNED :::::: " << resultSize << endl;
This is what is printed:
BYTES ::: 0 0 4 0
SIZE RETURNED :::::: 262144
And I’m expecting resultSize to be 1024.
Why does resultSize contain 262144 intead of 1024?
You’d get the conversion you expect on a machine with a “big-endian” processor, like a 68000-series. On Intel processors — “little-endian” machines — the byte order is reversed, and the answer you got is the expected one.
Converting raw memory bytes into into data types like
int,double, etc, is tricky, and if the data potentially comes from another machine, very tricky. There are semi-standard functions calledntohs(),ntohl(),htons(), andhtonl()which convert between host-specific order and standard “network order”, which is big-endian; these functions are available on all UNIX-like systems and in some Windows C libraries, as well.