用字節工作,我想寫科特林代碼,如:按位與不科特林
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
用字節工作,我想寫科特林代碼,如:按位與不科特林
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
歌林提供可用的位運算符樣infix functions只Int
和Long
。
所以有必要字節轉換爲整數來進行按位老年退休金計劃:
val b : Byte = 127
val res = (b.toInt() and 0x0f).toByte() // evaluates to 15
UPDATE: 由於科特林1.1這些操作都可以直接在字節。
從bitwiseOperations.kt:
@SinceKotlin("1.1")
public inline infix fun Byte.and(other: Byte): Byte = (this.toInt() and other.toInt()).toByte()
這也是有用的注意,java也做這個擴大轉換。這只是隱含的。 – Raman
按位「和」任意字節值和0xFF的總是會返回原來的價值。
它是簡單的看這個,如果你在圖中畫出位:
00101010 42
11111111 and 0xff
--------
00101010 gives 42
能否請您解釋一下你的代碼做什麼?我從來沒有在 – voddan