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

℡╲_俬逩灬. 提交于 2020-01-17 09:11:09

问题


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?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/5712066/send-a-int-from-objective-c-to-java-by-socket-but-the-value-changed-in-java-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!