Kotlin位移操作

7
我希望您能将此答案的代码转换为Kotlin:https://dev59.com/AHA65IYBdhLWcg3w-z5A#5402769 我将其粘贴到Intellij中:
private int decodeInt() {
    return ((bytes[pos++] & 0xFF) << 24) | ((bytes[pos++] & 0xFF) << 16)
            | ((bytes[pos++] & 0xFF) << 8) | (bytes[pos++] & 0xFF);
}

当我在Intellij中选择将代码转换为Kotlin时,会得到以下输出:
private fun decodeInt(): Int {
    return (bytes[pos++] and 0xFF shl 24 or (bytes[pos++] and 0xFF shl 16)
            or (bytes[pos++] and 0xFF shl 8) or (bytes[pos++] and 0xFF))
}

在任何时候,我都会遇到这个错误:0xFF
The integer literal does not conform to the expected type Byte

在它后面添加 .toByte() 之后,我能够解决这个错误。

在所有的左移操作(shl)中,我都会遇到这个错误:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 

@SinceKotlin @InlineOnly public infix inline fun BigInteger.shl(n: Int): BigInteger defined in kotlin

我无法解决这个问题... 我对Java/Kotlin中的位移操作并不了解...
这个问题的Kotlin代码应该是什么呢?

2个回答

14

像这样明确地进行转换:0xFF.toByte()

一般规则是,当您需要了解有关错误或可能解决方案的更多信息时,请按Alt+Enter。

shift left方法需要一个Int类型的参数。因此,同样的事情,需要将其转换为正确的类型。

(bytes[pos++] and 0xFF.toByte()).toInt() shl 24

这段代码有8次转换。虽然它能运行,但只需要4次转换就可以完成。 - Paul Hicks
@Paul Hicks 你可能是对的。我会反驳你的负评,因为我不认为你的回答有什么不好,而且那个给负评的人也没有说出问题所在。 - DPM

2

shl函数需要的是Int类型,而不是Byte类型。你需要使用0xFF来表示一个Int类型(它本身就是Int类型),所以不要调用toByte()方法。你需要使用(0xFF shl 24)来表示一个Int类型,所以不要进行转换。你需要将bytes[pos++]转换为Int类型...请注意!

return (((bytes[pos++].toInt() and (0xFF shl 24)) or
         (bytes[pos++].toInt() and (0xFF shl 16)) or
         (bytes[pos++].toInt() and (0xFF shl 8)) or
         (bytes[pos++].toInt() and 0xFF))

1
或者更好的方法是将“bytes”更改为Int数组,而不是Byte数组。在大多数情况下,这样会更快,尽管会使用更多的内存。 - Paul Hicks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接