繁体   English   中英

如何使用 Kotlin 将 ByteArray 转换为 Int?

[英]How can I convert a ByteArray to an Int with Kotlin?

如何使用 Kotlin 将 ByteArray 转换为 Int?

我在 Java 中使用的代码:

return ((buffer[offset++] & 0xff) << 24) |
       ((buffer[offset++] & 0xff) << 16) |
       ((buffer[offset++] & 0xff) << 8) |
       (buffer[offset] & 0xff);

我在 Kotlin 中尝试了这段代码:

return (buffer[offset++] and 0xff shl 24) or
       (buffer[offset++] and 0xff shl 16) or
       (buffer[offset++] and 0xff shl 8) or
       (buffer[offset] and 0xff)

但它返回以下关于“和”运算符的警告:

由于接收器类型不匹配,以下候选均不适用

感谢@a_local_nobody,我设法解决了这个问题:

return (buffer[offset++].toInt() and 0xff shl 24) or
        (buffer[offset++].toInt() and 0xff shl 16) or
        (buffer[offset++].toInt() and 0xff shl 8) or
        (buffer[offset].toInt() and 0xff)

我做了一些阅读,似乎像andorshl这样的按位运算仅在 Kotlin 中为 Int 和 Long 定义。

来自文档

在此处输入图像描述

如果你想使用它们,你必须转换它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM