如何将Int转换为ByteArray,然后使用Kotlin将其转换回Int?

q3qa4bjr  于 2023-08-06  发布在  Kotlin
关注(0)|答案(4)|浏览(149)

下面是我的代码:

Int ->字节数组

private fun write4BytesToBuffer(buffer: ByteArray, offset: Int, data: Int) {
    buffer[offset + 0] = (data shr 24).toByte()
    buffer[offset + 1] = (data shr 16).toByte()
    buffer[offset + 2] = (data shr 8).toByte()
    buffer[offset + 3] = (data shr 0).toByte()
}

字符串

字节数组-> Int

private fun read4BytesFromBuffer(buffer: ByteArray, offset: Int): Int {
    return (buffer[offset + 0].toInt() shl 24) or
           (buffer[offset + 1].toInt() shl 16) or
           (buffer[offset + 2].toInt() shl 8) or
           (buffer[offset + 3].toInt() and 0xff)
}


对于**-32,76832,767**之间的任何值,它都不会有任何问题。但是,它不适用于较大的值。举例来说:

val buffer = ByteArray(10)
write4BytesToBuffer(buffer, 0, 324)
read4BytesFromBuffer(buffer, 0) // It returns 324 ***OK***

val buffer = ByteArray(10)
write4BytesToBuffer(buffer, 0, 40171)
read4BytesFromBuffer(buffer, 0) // It returns -25365 ***ERROR***


你知道我错在哪里了吗?

cngwdvgl

cngwdvgl1#

这是解决方案。

Int ->字节数组

private fun write4BytesToBuffer(buffer: ByteArray, offset: Int, data: Int) {
    buffer[offset + 0] = (data shr 0).toByte()
    buffer[offset + 1] = (data shr 8).toByte()
    buffer[offset + 2] = (data shr 16).toByte()
    buffer[offset + 3] = (data shr 24).toByte()
}

字符串
或者用更短的方式

for (i in 0..3) buffer[offset + i] = (data shr (i*8)).toByte()

字节数组-> Int

private fun read4BytesFromBuffer(buffer: ByteArray, offset: Int): Int {
    return (buffer[offset + 3].toInt() shl 24) or
           (buffer[offset + 2].toInt() and 0xff shl 16) or
           (buffer[offset + 1].toInt() and 0xff shl 8) or
           (buffer[offset + 0].toInt() and 0xff)
}

9fkzdhlc

9fkzdhlc2#

我会用java.nio.ByteBuffer-

fun intToBytes(i: Int): ByteArray =
    ByteBuffer.allocate(Int.SIZE_BYTES).putInt(i).array()

fun bytesToInt(bytes: ByteArray): Int =
    ByteBuffer.wrap(bytes).int

字符串

b4lqfgs4

b4lqfgs43#

这里有一个行程序,它会给予你一个ByteArray:

fun numberToByteArray (data: Number, size: Int = 4) : ByteArray = 
    ByteArray (size) {i -> (data.toLong() shr (i*8)).toByte()}

字符串
可选地设置字节数(大小),您可以转换Shorts,Ints,Long.
就这么叫吧:

var yourByteArray = numberToByteArray (yourNumberHere)

wmvff8tz

wmvff8tz4#

你可以写一个extension function

fun ByteArray.getIntAt(i: Int): Int {
    return (this[i].toInt() and 0xFF) or
            ((this[i + 1].toInt() and 0xFF) shl 8) or
            ((this[i + 2].toInt() and 0xFF) shl 16) or
            ((this[i + 3].toInt() and 0xFF) shl 24)
}

字符串
现在你可以使用它:

val myInt = myByteArr.getIntAt(myIndex)


反之亦然:

private fun Int.toByteArray(): ByteArray {
    return byteArrayOf(
        (this and 0xFF).toByte(),
        ((this shr 8) and 0xFF).toByte(),
        ((this shr 16) and 0xFF).toByte(),
        ((this shr 24) and 0xFF).toByte()
    )
}


并使用它:

val myByteArray = myInt.toByteArray()

相关问题