Search code examples
arrayskotlinintegerbyte

How can I convert an Int to a ByteArray and then convert it back to an Int with Kotlin?


Here is my code :

Int -> ByteArray

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

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

It works without any problem for any value between -32,768 and 32,767. However, it doesn't work with larger values. For example :

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***

Do you see where I went wrong?


Solution

  • Here is the solution.

    Int -> ByteArray

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

    Or in a shorter way

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

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