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?
ByteBuffer
as described here: #4485628 – Phago