好的方法来访问混合8/16/32位字

我在内存中有大量的二进制数据,我需要从随机访问的字节对齐地址读取/写入数据。 然而,有时我需要读/写8位字,有时候是(big-endian)16位字,有时候是(big-endian)32位字。

将数据表示为ByteArray并手工实现16/32位读/写是一种天真的解决方案:

 class Blob (val image: ByteArray, var ptr: Int = 0) { fun readWord8(): Byte = image[ptr++] fun readWord16(): Short { val hi = readWord8().toInt() and 0xff val lo = readWord8().toInt() and 0xff return ((hi shl 8) or lo).toShort() } fun readWord32(): Int { val hi = readWord16().toLong() and 0xffff val lo = readWord16().toLong() and 0xffff return ((hi shl 16) or lo).toInt() } } 

(和writeWord8 / writeWord16 / writeWord32 )。

有没有更好的方法来做到这一点? 当Java本身已经在内部使用big-endian表示法的时候,看起来效率很低

重申一下,我需要读写访问随机查找 ,以及8/16/32 位访问大端字。

您可以使用Java NIO ByteBuffer

 val array = ByteArray(100) val buffer = ByteBuffer.wrap(array) val b = buffer.get() val s = buffer.getShort() val i = buffer.getInt() buffer.put(0.toByte()) buffer.putShort(0.toShort()) buffer.putInt(0) buffer.position(10) 

新创建的ByteBuffer的字节顺序是BIG_ENDIAN ,但仍然可以使用order(ByteOrder)函数进行更改。

另外,如果你想避免创建一个ByteArray你可以使用ByteBuffer.allocate(size)buffer.array()

有关ByteBuffer用法的更多信息: 请参阅此问题 。