ByteBuffer Little Endian插入不起作用

时间:2012-11-25 17:12:51

标签: java android bytebuffer endianness

我必须在遗留系统和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]

那么我错过了什么?

2 个答案:

答案 0 :(得分:31)

出于某些奇怪的原因,您将重新初始化字节缓冲区并丢弃先前已更改字节顺序的副本。以下代码对我来说很合适:

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]

答案 1 :(得分:0)

在相关说明中:

此代码:

 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 ++,第一种方法是我找到的最快的方法。好奇它比第二个片段更快。