按位&不适用于kotlin中的字节 [英] bitwise & doesn't work with bytes in kotlin

查看:349
本文介绍了按位&不适用于kotlin中的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写类似以下内容的kotlin代码:

I'm trying to write kotlin code like:

for (byte b : hash)  
     stringBuilder.append(String.format("%02x", b&0xff));

但与&"无关.我正在尝试使用"b和0xff",但是它不起作用.按位的和"似乎对Int起作用,而不对字节起作用.

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))

可以使用

1 and 0xff

推荐答案

Kolin提供类似于按位运算符的中缀功能仅适用于IntLong.

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

更新: 从Kotlin 1.1开始,这些操作可直接在Byte上进行.

UPDATE: Since Kotlin 1.1 these operations are available directly on Byte.

来自 bitwiseOperations.kt :

@SinceKotlin("1.1") 
public inline infix fun Byte.and(other: Byte): Byte = (this.toInt() and other.toInt()).toByte()

这篇关于按位&不适用于kotlin中的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆