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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With