Byte
Array
大小4 的a的内容如下:
{1, 0, 0, 0}
。使用时,这将转换为1
C#中的整数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)
}
我相信两种转换方法都是正确的,并且字节值未签名。
如@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
}