按位&不适用于kotlin中的字节
我正在努力写下kotlin代码:
for (byte b : hash) stringBuilder.append(String.format("%02x", b&0xff));
但是我与“&”无关。 我试图使用“b和0xff”,但它不起作用。 按位“和”似乎工作在INT,而不是字节。
java.lang.String.format("%02x", (b and 0xff))
可以使用
1 and 0xff
Kolin只提供了Int
和Long
按位运算符类中缀函数 。
所以有必要将字节转换为整数来执行按位操作:
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()
按位“和”任何字节值和0xff将始终返回原始值。
如果您在图中绘制位,很容易看出这一点:
00101010 42 11111111 and 0xff -------- 00101010 gives 42