bitwise & doesn't work with bytes in kotlin

前端 未结 2 1098
渐次进展
渐次进展 2020-12-16 10:33

I\'m trying to write kotlin code like:

for (byte b : hash)  
     stringBuilder.append(String.format(\"%02x\", b&0xff));

but I have not

2条回答
  •  有刺的猬
    2020-12-16 11:06

    Kolin provides bitwise operator-like infix functions available for Int and Long only.

    So it's necessary to convert bytes to ints to perform bitwise ops:

    val b : Byte = 127
    val res = (b.toInt() and 0x0f).toByte() // evaluates to 15
    

    UPDATE: Since Kotlin 1.1 these operations are available directly on Byte.

    From bitwiseOperations.kt:

    @SinceKotlin("1.1") 
    public inline infix fun Byte.and(other: Byte): Byte = (this.toInt() and other.toInt()).toByte()
    

提交回复
热议问题