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

How to write Short/Int into 1 byte buffer

我有这些功能:

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()
}