按位 & 不适用于 kotlin 中的字节

bitwise & doesn't work with bytes in kotlin

我正在尝试编写如下的 Kotlin 代码:

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

但我与“&”无关。我正在尝试使用 "b and 0xff" 但它不起作用。按位 "and" 似乎适用于 Int,而不适用于字节。

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

可以用

1 and 0xff

任何字节值的按位 "and" 和 0xff 将始终 return 原始值。

如果你在图中画出这些位,就很容易看出这一点:

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

Kolin 提供类似位运算符的 infix functions,仅适用于 IntLong

因此有必要将字节转换为整数以执行按位操作:

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

更新: 自 Kotlin 1.1 起,这些操作可直接在 Byte 上使用。

来自bitwiseOperations.kt:

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