温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Convert Byte Array to Int odd result Java and Kotlin
android c# java kotlin

c# - 将字节数组转换为Int奇数结果Java和Kotlin

发布于 2020-03-27 11:41:16

Byte Array大小4 的a的内容如下: {1, 0, 0, 0}使用时,这将转换为1C#中的整数BitConverter.ToInt32(bytearray, 0);

但是,Integer在使用以下代码库将此字节数组转换为Kotlin中的时,我得到的是值16777216而不是1

var test0 = BigInteger(bytearray).toInt() = 16777216
var test1 = BigInteger(bytearray).toFloat() = 1.6777216        

要么

fun toInt32(bytes: ByteArray, index: Int): Int
{
    if (bytes.size != 4) 
        throw Exception("The length of the byte array must be at least 4 bytes long.")

    return 0xff 
        and bytes[index].toInt() shl 56 
        or (0xff and bytes[index + 1].toInt() shl 48) 
        or (0xff and bytes[index + 2].toInt() shl 40) 
        or (0xff and bytes[index + 3].toInt() shl 32)
}

我相信两种转换方法都是正确的,并且字节值未签名。

查看更多

查看更多

提问者
George
被浏览
98
2,638 2019-07-31 18:36

如@Lother及其its86所建议。

fun littleEndianConversion(bytes: ByteArray): Int {
    var result = 0
    for (i in bytes.indices) {
        result = result or (bytes[i].toInt() shl 8 * i)
    }
    return result
}