MeloS
MeloS

Reputation: 7938

send a int from objective-c to java by socket,but the value changed in java side

I send a int in a NSData like this:

 NSData* dataLength = [[NSData alloc] initWithBytes:&theInt length:sizeof(theInt)];

then in java side, I get a int like this:

int theInt = aInputStreamOfSocket.readInt();

but the value changed! In my case, I send 1225516 and get 749933056 what's the problem?

Upvotes: 0

Views: 915

Answers (2)

Tom Dalling
Tom Dalling

Reputation: 24125

Let's look at the hex for both of those numbers

1225516   = 0x0012B32C  
749933056 = 0x2CB31200

You can see that the byte order (a.k.a. endianness) is reversed.

Generally, if you're sending data over a socket, you convert from the local byte order to network byte order with the functions htonl, htons, etc. On the receiving end, you convert from network byte order back to the local byte order. In java, you can do this by setting the byte order on the buffer with ByteBuffer#order(ByteOrder)

See this question also.

Upvotes: 1

WhiteFang34
WhiteFang34

Reputation: 72039

Your trouble is a difference in endianness. Intel based processors use little-endian byte order while network based transports are almost always big-endian. Java thus expects big-endian for readInt(). Ideally you find a way to send the int as big-endian to conform to expected behavior. I however don't have that code offhand, so here's how to read little-endian on the Java side:

int ch1 = aInputStreamOfSocket.read();
int ch2 = aInputStreamOfSocket.read();
int ch3 = aInputStreamOfSocket.read();
int ch4 = aInputStreamOfSocket.read();
if ((ch1 | ch2 | ch3 | ch4) < 0) {
    throw new EOFException();
}
int theInt = ch1 + (ch2 << 8) + (ch3 << 16) + (ch4 << 24);

Upvotes: 2

Related Questions