Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convertion to and from the byte array

Recently I'm trying to make a byte array from an object of class containing a few variables of primitive types. The problem has began with saving a double to the 8-byte format. After getting it back retrieved value isn't the same but kind of very close.

First I checked such expression val value = Double.fromBits(1.2.toBits()) and it gave me a correct answer. So, I guess there's something wrong with my implementation of moving long integer into byte array but I can't find the bug.

Samples below and I'll be really greatful for any suggestion. Cheers!

Writing to byte array:

fun from(value : Long) : ByteArray{
    val byteArray = ByteArray(Long.SIZE_BYTES)
    var index = 0
    var shift = 8 * Long.SIZE_BYTES

     while(index < Long.SIZE_BYTES){
        shift -= 8
        byteArray[index] = value.shr(shift).and(0xFFL).toByte()
        index++
     }

     return byteArray
}

Reading from byte array:

fun read(byteArray: ByteArray) : Long{
    var value = 0L
    var index = 0

    while(index < Long.SIZE_BYTES){
        value = value.shl(8) + byteArray[index].toLong()
        index++
    }

    return value
}
like image 584
Giebut Avatar asked Oct 24 '25 15:10

Giebut


1 Answers

Your read() does not work correctly for negative bytes. You need to remember that while positive numbers are "padded" with zeros, negative numbers are padded with ones. Shifting right or widening an integer adds 0 or 1 depending on the sign.

The error is in this line:

value = value.shl(8) + byteArray[index].toLong()

You expected that the byte FF after converting to long would become 0x00000000000000FF, but in fact, it is 0xFFFFFFFFFFFFFFFF. You need to AND it with 0xFF to acquire only the lowest byte:

value = value.shl(8) + byteArray[index].toLong().and(0xFF)
like image 179
broot Avatar answered Oct 26 '25 17:10

broot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!