I'm trying to write kotlin code like:
for (byte b : hash) stringBuilder.append(String.format("%02x", b&0xff));
but I have nothing to do with the "&". I'm trying to use "b and 0xff" but it doesn't work. The bitwise "and" seems to work on Int, not byte.
java.lang.String.format("%02x", (b and 0xff))
it's ok to use
1 and 0xff
Bitwise is a level of operation that involves working with individual bits which are the smallest units of data in a computing system. Each bit has single binary value of 0 or 1. Most programming languages manipulate groups of 8, 16 or 32 bits. These bit multiples are known as bytes.
Invest in the companies leading the new crypto economy. BITQ tracks an index designed with Bitwise's industry expertise to identify the pioneering companies that generate the majority of their revenue from their crypto business activities. It's a traditional ETF.
The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.
Kolin provides bitwise operator-like infix functions available for Int
and Long
only.
So it's necessary to convert bytes to ints to perform bitwise ops:
val b : Byte = 127 val res = (b.toInt() and 0x0f).toByte() // evaluates to 15
UPDATE: Since Kotlin 1.1 these operations are available directly on Byte.
From bitwiseOperations.kt:
@SinceKotlin("1.1") public inline infix fun Byte.and(other: Byte): Byte = (this.toInt() and other.toInt()).toByte()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With