25

我必须在遗留系统和安卓设备之间进行双向通信。遗留系统使用小端字节序。我已经成功实现了接收部分,但是发送不起作用。

奇怪,因为对我来说似乎 ByteBuffer 类出现故障(我简直不敢相信)

    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer = ByteBuffer.allocate(4);
    byteBuffer.putInt(88);
    byte[] result = byteBuffer.array();

结果:[0, 0, 0, 88]

    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    byteBuffer.order(ByteOrder.BIG_ENDIAN);
    byteBuffer = ByteBuffer.allocate(4);
    byteBuffer.putInt(88);
    byte[] result = byteBuffer.array();

结果也相同: [0, 0, 0, 88]

但是,如果我没记错小端排序应该返回: [88, 0, 0, 0]

那么我错过了什么?

4

2 回答 2

37

出于某种奇怪的原因,您正在重新初始化字节缓冲区并丢弃以前更改字节序的副本。以下代码对我来说很好用:

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.order(ByteOrder.BIG_ENDIAN);
byteBuffer.putInt(88);
byte[] result = byteBuffer.array();
System.out.println(Arrays.toString(result));

打印 [0, 0, 0, 88]

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.putInt(88);
byte[] result = byteBuffer.array();
System.out.println(Arrays.toString(result));

打印 [88, 0, 0, 0]

于 2012-11-25T17:28:06.633 回答
1

在相关说明中:

这段代码:

 int unicodePointsLen = textContent.length() * 2;
 ByteBuffer unicodePointsBuffer = ByteBuffer.allocateDirect(unicodePointsLen);
 short unicodePointValue;
 for (int i = 0; i < textContent.length(); i++) 
 {  
     unicodePointValue = (short)textContent.charAt(i);
     unicodePointsBuffer.put((byte)(unicodePointValue & 0x00FF)).put((byte)(unicodePointValue >> 8));
 }

比这快大约 25%:

 int unicodePointsLen = textContent.length() * 2;
 ByteBuffer unicodePointsBuffer = ByteBuffer.allocateDirect(unicodePointsLen);
 unicodePointsBuffer.order(ByteOrder.LITTLE_ENDIAN);
 for (int i = 0; i < textContent.length(); i++) 
 {  
     unicodePointsBuffer.putShort((short)textContent.charAt(i));  
 }

使用 JDK 1.8。

I am trying to pass unicode points from JAVA to C++ through JNI and the first method is the fastest I found. Curious that it is faster than the second snippet.

于 2014-12-30T22:12:11.110 回答