Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise & doesn't work with bytes in kotlin

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 
like image 487
Allen Vork Avatar asked Oct 29 '15 10:10

Allen Vork


People also ask

What bitwise means?

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.

What is bitwise Crypto?

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.

How does bitwise work?

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.


1 Answers

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() 
like image 195
Vadzim Avatar answered Sep 23 '22 18:09

Vadzim