Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 679
George Avatar asked Jul 03 '19 14:07

George


3 Answers

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
}
like image 132
George Avatar answered Nov 10 '22 04:11

George


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
    }
like image 41
android developer Avatar answered Nov 10 '22 06:11

android developer


Here is,

   fun toInt32(bytes:ByteArray):Int {
       if (bytes.size != 4) { 
           throw Exception("wrong len")
       }                   
       bytes.reverse()          
       return ByteBuffer.wrap(bytes).int           
   }
like image 2
eigenfield Avatar answered Nov 10 '22 06:11

eigenfield