Using this answer to the question "How do I convert Long to byte[] and back in Java":
import java.nio.ByteBuffer
import java.util.Base64
fun main() {
val number: Long = 12345678
val encodedNumberString = Base64.getEncoder().encodeToString(longToBytes(number))
println("Number: $number.")
println("Encoded number: \"$encodedNumberString\".")
val decodedNumberBytes = Base64.getDecoder().decode(encodedNumberString)
val decodedNumber = bytesToLong(decodedNumberBytes)
println("Decoded number: $decodedNumber.")
}
private fun longToBytes(number: Long): ByteArray {
val buffer = ByteBuffer.allocate(java.lang.Long.BYTES)
buffer.putLong(number)
return buffer.array()
}
private fun bytesToLong(bytes: ByteArray): Long {
val buffer = ByteBuffer.allocate(java.lang.Long.BYTES)
buffer.put(bytes)
// Prepare the byte buffer to enable reading from it.
buffer.flip()
return buffer.long
}
This is the output on my system:
Number: 12345678.
Encoded number: "AAAAAAC8YU4=".
Decoded number: 12345678.
Update: Base64
Base64 is a way to convert binary data to text and uses a safe subset of 64 characters that can be transferred in for example an e-mail attachment. Not all 256 values in a byte can be sent without problems, so only 6 bits (2^6 = 64) are encoded in each character. This means that 3 bytes can be transferred in 4 characters (the overhead is 33%).
Update: extension functions
As Alex.T already mentioned in the comment, Kotlin enables you to make the Long <-> ByteArray conversions a lot shorter using extension functions (assuming the ByteArray implementation has an accessible backing array):
fun Long.toByteArray(): ByteArray = ByteBuffer.allocate(java.lang.Long.BYTES).apply { putLong(this@toByteArray) }.array()
fun ByteArray.toLong(): Long = ByteBuffer.allocate(java.lang.Long.BYTES).apply { put(this@toLong); flip() }.long
fun main() {
val number = 12345678L
val encodedNumberString = Base64.getEncoder().encodeToString(number.toByteArray())
println("Encoded number: \"$encodedNumberString\".")
val decodedNumber = Base64.getDecoder().decode(encodedNumberString).toLong()
println("Decoded number: $decodedNumber.")
}