DP_*_*DP_ 23 types type-conversion kotlin
想象一下,我有一个带有变量b类型的Kotlin程序,Byte外部系统写入的值大于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")
}
Run Code Online (Sandbox Code Playgroud)
更新1:Thilo建议的解决方案似乎有效.
private fun magicallyExtractRightValue(o: Byte): Int = when {
(o.toInt() < 0) -> 255 + o.toInt() + 1
else -> o.toInt()
}
Run Code Online (Sandbox Code Playgroud)
mfu*_*n26 33
使用Kotlin 1.3+,您可以使用无符号类型.例如toUByte(Kotlin游乐场):
private fun magicallyExtractRightValue(b: Byte): Int {
return b.toUByte().toInt()
}
Run Code Online (Sandbox Code Playgroud)
甚至要求UByte直接使用Byte(Kotlin Playground):
private fun magicallyExtractRightValue(b: UByte): Int {
return b.toInt()
}
Run Code Online (Sandbox Code Playgroud)
对于发布到科特林1.3之前,我建议创建一个扩展功能,这一点使用做and:
fun Byte.toPositiveInt() = toInt() and 0xFF
Run Code Online (Sandbox Code Playgroud)
用法示例:
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")
Run Code Online (Sandbox Code Playgroud)
示例输出:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7914 次 |
| 最近记录: |