All*_*ork 19 bit-manipulation kotlin
我正在尝试写kotlin代码,如:
for (byte b : hash)
stringBuilder.append(String.format("%02x", b&0xff));
Run Code Online (Sandbox Code Playgroud)
但我与"&"无关.我正在尝试使用"b和0xff"但它不起作用.按位"和"似乎适用于Int,而不是字节.
java.lang.String.format("%02x", (b and 0xff))
Run Code Online (Sandbox Code Playgroud)
可以使用
1 and 0xff
Run Code Online (Sandbox Code Playgroud)
Vad*_*zim 30
Kolin提供类似于运算符的按位中继功能Int
,Long
仅适用于.
因此有必要将字节转换为int以执行按位运算:
val b : Byte = 127
val res = (b.toInt() and 0x0f).toByte() // evaluates to 15
Run Code Online (Sandbox Code Playgroud)
更新: 从Kotlin 1.1开始,这些操作可直接在Byte上使用.
来自bitwiseOperations.kt:
@SinceKotlin("1.1")
public inline infix fun Byte.and(other: Byte): Byte = (this.toInt() and other.toInt()).toByte()
Run Code Online (Sandbox Code Playgroud)
任何字节值和0xff的按位"和"将始终返回原始值.
如果您在图中绘制位,很容易看到这个:
00101010 42
11111111 and 0xff
--------
00101010 gives 42
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10335 次 |
最近记录: |