0

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?

1
  • 3
    Looks like you are expecting big-endian behavior on a little-endian system. Commented May 7, 2012 at 3:15

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! The data is comming from the same mahine but from a java vm. I didn't know that jvm was big endian. Thanks!
Indeed, it is. Java is always big endian, even on Intel hardware. That means it always communicates in "network byte order", which is a good feature for a network-facing language.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.