如何正确处理Kotlin中大于127的字节值?

想象一下,我有一个带有Byte类型的变量b的Kotlin程序,外部系统写入的值大于127 。 “外部”意味着我不能改变它返回的值的类型。

val a:Int = 128 val b:Byte = a.toByte()

a.toByte()b.toInt()返回-128

想象一下,我想从变量b得到正确的值( 128 )。 我该怎么做?

换句话说: magicallyExtractRightValue什么实现会使下面的测试运行?

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

我建议创建一个扩展功能来做到这一点使用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]