如何正确处理Kotlin中大于127的字节值? [英] How to correctly handle Byte values greater than 127 in Kotlin?
问题描述
想象一下,我有一个Kotlin程序,其类型为Byte
的变量b
,外部系统在其中写入了大于127
的值. 外部"表示我无法更改其返回值的类型.
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()
val a:Int = 128
val b:Byte = a.toByte()
a.toByte()
和b.toInt()
都返回-128
.
想象一下我想从变量b
获得正确的值(128
).我该怎么办?
Imagine I want to get the correct value (128
) from the variable b
. How can I do it?
换句话说:magicallyExtractRightValue
的哪种实现将使以下测试运行?
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")
}
更新1:此解决方案由 Thilo 建议.
private fun magicallyExtractRightValue(o: Byte): Int = when {
(o.toInt() < 0) -> 255 + o.toInt() + 1
else -> o.toInt()
}
推荐答案
使用Kotlin 1.3+,您可以使用 toUByte
(
With Kotlin 1.3+ you can use unsigned types. e.g. toUByte
(Kotlin Playground):
private fun magicallyExtractRightValue(b: Byte): Int {
return b.toUByte().toInt()
}
甚至需要直接使用UByte
代替Byte
(科特琳游乐场):>
or even require using UByte
directly instead of Byte
(Kotlin Playground):
private fun magicallyExtractRightValue(b: UByte): Int {
return b.toInt()
}
对于Kotlin 1.3之前的版本,我建议创建一个扩展功能使用 and
:
For releases prior to Kotlin 1.3, I recommend creating an extension function to do this using and
:
fun Byte.toPositiveInt() = toInt() and 0xFF
示例用法:
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")
示例输出:
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]
这篇关于如何正确处理Kotlin中大于127的字节值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!