简体   繁体   中英

Convert Byte Array to Int odd result Java and Kotlin

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.

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
}

A tiny bit different solution which I think is a bit more efficient:

    private fun byteToInt(bytes: ByteArray): Int {
        var result = 0
        var shift = 0
        for (byte in bytes) {
            result = result or (byte.toInt() shl shift)
            shift += 8
        }
        return result
    }

Here is,

   fun toInt32(bytes:ByteArray):Int {
       if (bytes.size != 4) { 
           throw Exception("wrong len")
       }                   
       bytes.reverse()          
       return ByteBuffer.wrap(bytes).int           
   }

Similar to eigenfeld's answer, but without needing to reverse the bytes first.

fun toInt32(bytes: ByteArray, index: Int): Int {
    require(bytes.size == 4) { "length must be 4, got: ${bytes.size}" }
    return ByteBuffer.wrap(bytes, index, 4).order(ByteOrder.LITTLE_ENDIAN).int
}

在 C# 中,您有以下类:

var test0 = BitConverter.ToInt32(bytearray, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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