我试图编写类似以下的 Kotlin 代码:
for (byte b : hash)
stringBuilder.append(String.format("%02x", b&0xff));
但是我与"&"无关。 我尝试使用"b and 0xff",但它不起作用。 按位"and"似乎在Int上有效,而不是byte。
java.lang.String.format("%02x", (b and 0xff))
可以使用
1 and 0xff
我试图编写类似以下的 Kotlin 代码:
for (byte b : hash)
stringBuilder.append(String.format("%02x", b&0xff));
但是我与"&"无关。 我尝试使用"b and 0xff",但它不起作用。 按位"and"似乎在Int上有效,而不是byte。
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
int
(Kotlin要求这一点必须显式)。因此,为了使这种扩展转换在初始字节值为负数时产生预期的正整数值,需要通过& 0xff
掩码来屏蔽扩展后的int值的3个高阶字节(其中包括符号位)。 - Ramanx & 0xff
是一种很酷的转换为整数的方式。谢谢,我现在要到处使用它。这会让我看起来很聪明! - Sarsaparilla
java.lang.String.format
,而是使用byte.toString(2)
。 - Adam Millerchip