问题
Imagine I have a Kotlin program with a variable b
of type Byte
, into which an external system writes values greater than 127
. "External" means that I cannot change the type of the value it returns.
val a:Int = 128
val b:Byte = a.toByte()
Both a.toByte()
and b.toInt()
return -128
.
Imagine I want to get the correct value (128
) from the variable b
. How can I do it?
In other words: What implementation of magicallyExtractRightValue
would make the following test run?
@Test
fun testByteConversion() {
val a:Int = 128
val b:Byte = a.toByte()
System.out.println(a.toByte())
System.out.println(b.toInt())
val c:Int = magicallyExtractRightValue(b)
Assertions.assertThat(c).isEqualTo(128)
}
private fun magicallyExtractRightValue(b: Byte): Int {
throw UnsupportedOperationException("not implemented")
}
Update 1: This solution suggested by Thilo seems to work.
private fun magicallyExtractRightValue(o: Byte): Int = when {
(o.toInt() < 0) -> 255 + o.toInt() + 1
else -> o.toInt()
}
回答1:
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]
回答2:
Good old printf
does what we want:
java.lang.String.format("%02x", byte)
来源:https://stackoverflow.com/questions/38651192/how-to-correctly-handle-byte-values-greater-than-127-in-kotlin