如何将Short / Int写入1字节缓冲区

我有这些功能:

fun asByteArray(value: Short): ByteArray { val buffer: ByteBuffer = ByteBuffer.allocate(2) buffer.order(ByteOrder.BIG_ENDIAN) buffer.putShort(value) buffer.flip() return buffer.array() } fun asByteArray(value: Int): ByteArray { val buffer: ByteBuffer = ByteBuffer.allocate(4) buffer.order(ByteOrder.BIG_ENDIAN) buffer.putInt(value) buffer.flip() return buffer.array() } 

如果值是255,那么我想写入1个字节的缓冲区。 我该怎么做? 如果我做ByteBuffer.allocate(1)并尝试写入short / int值,则发生BufferOverflowException。

不要直接写入Int ,写入value.toByte()的结果:

 fun asByteArray(value: Short): ByteArray { val buffer: ByteBuffer = ByteBuffer.allocate(1) buffer.put(value.toByte()) return buffer.array() } fun asByteArray(value: Int): ByteArray { val buffer: ByteBuffer = ByteBuffer.allocate(1) buffer.put(value.toByte()) return buffer.array() }