Andrei Sibircevs
Andrei Sibircevs

Reputation: 157

What is the difference between two conversions from Long to ByteArray?

import java.lang.Long as JLong
import java.lang.Byte as JByte
import java.nio.ByteBuffer

fun Long.toByteArray1() = 
    ByteBuffer.allocate(JLong.SIZE / JByte.SIZE)
        .putLong(this)
        .array()

fun Long.toByteArray2() =
    this.toString()
        .toByteArray(Charsets.UTF_8)

fun main(args: Array<String>) {
    val a1: ByteArray = 10L.toByteArray1()
    val a2: ByteArray = 10L.toByteArray2()
    println("a1 = ${a1.toString()}")
    println("a1 = ${ByteBuffer.wrap(a1).getLong()}")
    println("a2 = ${a2.toString()}")
    println("a2 = ${String(a2, Charsets.UTF_8)}")
}

What is the difference between toByteArray1() and toByteArray2()?

If I send the bytes into the outputstream what receiver will get?

Upvotes: 2

Views: 222

Answers (1)

hotkey
hotkey

Reputation: 148159

They are completely different.

  • .toByteArray1() returns bytes of the signed long number (therefore it should contain exactly 8 bytes = 64 bits):

    println(0.toByteArray1().size) // 8
    println(1234.toByteArray1().size) // 8
    
  • .toByteArray2() first converts the long to String and then to the byte array with the String characters encoded in UTF-8 (since there are only digits, they are encoded one byte each), and the byte array in this case contains the same number of bytes as the length of the string representation:

    println(0.toByteArray2().size) // 1
    println(-1234.toByteArray2().size) // 5
    println(123456789012.toByteArray2().size) // 12
    

And, of course, the decoders should be different, as in your example where you decode a1 and a2.

Upvotes: 3

Related Questions