【发布时间】:2016-12-03 17:18:07
【问题描述】:
假设我有一个 Kotlin 程序,其变量 b 类型为 Byte,外部系统向其中写入大于 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()
}
【问题讨论】:
-
byte是用 Java 签名的,所以你必须忍受这个。为什么必须使用byte?int来自哪里? -
我有一个外部库,我不想更改。它给了我带有负数的字节类型值。
-
所以图书馆已经给了你“-127”。为什么需要转换它?除非您以数字方式使用它,否则它不会产生影响。如果您确定该库确实“意味着” 128,则可以在结束时使用
short或int(通过对负数执行 255 + b 进行转换)。 -
我需要实际的数值,因为在另一个第三方库中,该数值被用作数组中的索引。
-
数组索引为
int。您可以通过int x = b < 0 ? 255 + b : b;从“无符号字节”转换
标签: types type-conversion kotlin