【问题标题】:How can I convert a ByteArray to an Int with Kotlin?如何使用 Kotlin 将 ByteArray 转换为 Int?
【发布时间】:2021-03-19 10:53:41
【问题描述】:

如何使用 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)

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

以下候选人均不适用,因为接收者 类型不匹配

【问题讨论】:

  • 如果我将 buffer[offset++] 替换为值 1,我似乎没有收到任何警告或错误,可能是您的缓冲区(或缓冲区内的类型)有问题) 也许?

标签: android kotlin type-conversion


【解决方案1】:

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

来自docs

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

【讨论】:

    【解决方案2】:

    感谢@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)
    

    【讨论】:

    • 啊,打败我了 :)
    猜你喜欢
    • 2021-07-14
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2010-10-28
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多