字节缓冲小字节序插入不起作用

2022-09-01 18:53:14

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

奇怪,因为对我来说,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]

那么我错过了什么呢?


答案 1

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

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]


答案 2

在相关说明中:

此代码:

 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。

我正在尝试通过JNI将unicode点从JAVA传递到C++,第一种方法是我找到的最快方法。奇怪的是它比第二个片段更快。


推荐