bitwise & doesn't work with bytes in kotlin

丶灬走出姿态 提交于 2019-12-09 07:54:04

问题


I'm trying to write kotlin code like:

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

but I have nothing to do with the "&". I'm trying to use "b and 0xff" but it doesn't work. The bitwise "and" seems to work on Int, not byte.

java.lang.String.format("%02x", (b and 0xff))

it's ok to use

1 and 0xff

回答1:


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



回答2:


Bitwise "and" of any byte-value and 0xff will always return the original value.

It is simple to see this if you draw the bits in a diagram:

00101010   42
11111111   and 0xff
--------
00101010   gives 42


来源:https://stackoverflow.com/questions/33411476/bitwise-doesnt-work-with-bytes-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!