How to correctly handle Byte values greater than 127 in Kotlin?

前端 未结 2 604
栀梦
栀梦 2021-02-05 02:38

Imagine I have a Kotlin program with a variable b of type Byte, into which an external system writes values greater than 127. \"External\"

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 03:21

    With Kotlin 1.3+ you can use 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 = listOf(0, 1, 63, 127, 128, 244, 255)
    println("from ints: $a")
    val b: List = a.map(Int::toByte)
    println("to bytes: $b")
    val c: List = b.map(Byte::toPositiveInt)
    println("to positive ints: $c")
    

    Example output:

    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]
    

提交回复
热议问题