How to correctly handle Byte values greater than 127 in Kotlin?
With Kotlin 1.3+ you can use unsigned types. e.g. toUByte
(Kotlin Playground):
private fun magicallyExtractRightValue(b: Byte): Int {
return b.toUByte().toInt()
}
or even require using UByte
directly instead of Byte
(Kotlin Playground):
private fun magicallyExtractRightValue(b: UByte): Int {
return b.toInt()
}
For releases prior to Kotlin 1.3, I recommend creating an extension function to do this using and
:
fun Byte.toPositiveInt() = toInt() and 0xFF
Example usage:
val a: List<Int> = listOf(0, 1, 63, 127, 128, 244, 255)
println("from ints: $a")
val b: List<Byte> = a.map(Int::toByte)
println("to bytes: $b")
val c: List<Int> = b.map(Byte::toPositiveInt)
println("to positive ints: $c")
Example output:
from ints: [0, 1, 63, 127, 128, 244, 255]
to bytes: [0, 1, 63, 127, -128, -12, -1]
to positive ints: [0, 1, 63, 127, 128, 244, 255]