Home > database >  Kotlin convertion to and from the byte array
Kotlin convertion to and from the byte array

Time:07-18

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
}

CodePudding user response:

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)
  • Related