gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:24:30 24 4
gpt4 key购买 nike

我有以下功能:

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

关于arrays - 如何将Short/Int写入1字节缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42534295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com