科特林位移

我想转换代码如果这个答案Kotlin: https : //stackoverflow.com/a/5402769/2735398

我把这个贴到了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代码呢?

像这样显式转换: 0xFF.toByte()

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

左移方法需要一个Int作为参数。 所以,同样的事情,转换为正确的types。

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

shl期望Int,而不是Byte。 你需要0xFF是一个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)) 
    Interesting Posts