Damian
Damian

Reputation: 5561

Getting int from char array

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?

Upvotes: 0

Views: 970

Answers (2)

Alexey Frunze
Alexey Frunze

Reputation: 62106

Apparently your system is big-endian, which means that least significant bytes of larger integers are at greater addresses and most significant bytes are at lower.

Little-endian result would be 0 + 4*256 + 0*2562 + 0*2563 = 1024

Big-endian result would be 0 + 0*256 + 4*2562 + 0*2563 = 262144

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81734

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 called ntohs(), ntohl(), htons(), and htonl() 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.

Upvotes: 3

Related Questions