假设我有一个Kotlin程序,它有一个类型为Byte的变量b,外部系统将大于127的值写入其中."External"表示我不能更改其返回值的类型.

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

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

假设我想要从变量b获得正确的值(128).我该怎么做呢?

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

推荐答案

使用Kotlin 1.3+可以使用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")

示例输出:

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相关问答推荐

在没有外部 map 的情况下转换列表项

最好的方法来创建一个 map 在kotlin从两个列表

Kotlin 海峡没有结束

Kotlin 说不需要强制转换,但删除后会出现新警告

Kotlin中反射中Int到可空Double的隐式转换失败

在kotlin中匹配多个变量

根据字符串值动态过滤数组列表 - kotlin

如何在 kotlin 中创建自定义迭代器并添加到现有类?

在子类中覆盖 kotlin 运算符扩展函数

高效匹配两个 Flux

如何在 Kotlin 中使用具有继承的泛型

Kotlin:内部类如何访问在外部类中声明为参数的变量?

对列表中数字的子集求和

如何使用 Coil 从 URL 获取位图?

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

如何用 kotlin 打包 List

Kotlin默认使用哪种排序?

@uncheckedVariance 在 Kotlin 中?

Android Jetpack Compose 中的文本渐变

Dagger 2 androidx fragment不兼容类型