【问题标题】:send a int from objective-c to java by socket,but the value changed in java side通过套接字从objective-c向java发送一个int,但是java端的值改变了
【发布时间】:2011-04-19 05:39:37
【问题描述】:

我像这样在 NSData 中发送一个 int:

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

然后在java端,我得到一个像这样的int:

int theInt = aInputStreamOfSocket.readInt();

但价值改变了!就我而言,我发送 1225516 并获得 749933056 有什么问题?

【问题讨论】:

    标签: java objective-c int


    【解决方案1】:

    您的麻烦在于endianness 的不同。基于 Intel 的处理器使用 little-endian 字节顺序,而基于网络的传输几乎总是 big-endian。因此,Java 期望 readInt() 采用大端序。理想情况下,您可以找到一种将 int 作为大端格式发送以符合预期行为的方法。然而,我手头没有该代码,所以这里是如何在 Java 端读取 little-endian:

    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】:

      让我们看看这两个数字的十六进制

      1225516 = 0x0012B32C 749933056 = 0x2CB31200

      您可以看到字节顺序(也称为字节序)被颠倒了。

      通常,如果您通过套接字发送数据,则使用 htonl、htons 等函数将本地字节顺序转换为网络字节顺序。在接收端,您从网络字节顺序转换回到本地字节顺序。在java中,你可以通过使用ByteBuffer#order(ByteOrder)设置缓冲区的字节顺序来做到这一点

      另见this question。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2015-08-31
        • 1970-01-01
        • 2023-04-03
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多