Warm tip: This article is reproduced from stackoverflow.com, please click
android c# java kotlin

Convert Byte Array to Int odd result Java and Kotlin

发布于 2020-03-27 10:26:59

The contents of a Byte Array of size 4 are the following: {1, 0, 0, 0}. This translates to the integer number 1 in C# when using BitConverter.ToInt32(bytearray, 0);

However, when converting this byte array to an Integer in Kotlin using the following code base I get the value 16777216 instead of the value of 1.

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

or

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)
}

I believe both methods of conversion are correct and the byte values are not signed.

Questioner
George
Viewed
595
2,638 2019-07-31 18:36

As suggested by @Lother and itsme86.

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