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

问题描述 投票:15回答:2

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

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

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

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

换句话说: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()
}
types type-conversion kotlin
2个回答
18
投票

使用Kotlin 1.3+,您可以使用unsigned types。例如toUByteKotlin Playground):

private fun magicallyExtractRightValue(b: Byte): Int {
    return b.toUByte().toInt()
}

甚至要求直接使用UByte而不是ByteKotlin Playground):

private fun magicallyExtractRightValue(b: UByte): Int {
    return b.toInt()
}

对于Kotlin 1.3之前的版本,我建议使用extension function创建一个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]

1
投票

好老printf做我们想要的:

java.lang.String.format("%02x", byte)
© www.soinside.com 2019 - 2024. All rights reserved.