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

Cac*_*tus 1 arrays io stream kotlin

我在内存中有大量的二进制数据,我需要从随机访问的字节对齐地址进行读/写.但是,有时候我需要读/写8位字,有时候(大端)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()
  }
}
Run Code Online (Sandbox Code Playgroud)

(和writeWord8/ writeWord16/ 类似writeWord32).

有一个更好的方法吗?当Java本身已经在内部使用big-endian表示时,执行所有这些字节混洗似乎效率很低......

重申一下,我需要读取和写入访问,随机搜索以及对big-endian字的8/16/32 位访问.

hot*_*key 5

您可以使用Java NIOByteBuffer:

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)
Run Code Online (Sandbox Code Playgroud)

新创建的字节顺序ByteBufferBIG_ENDIAN,但仍可以使用该order(ByteOrder)功能进行更改.

此外,使用ByteBuffer.allocate(size),buffer.array()如果你想避免创建一个ByteArray明确的.

更多关于ByteBuffer用法:看到这个问题.