Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Base64 encode an IntArray in Kotlin

Tags:

base64

kotlin

How to base64 encode a buff of intArrayOf using Kotlin.

val vec = intArrayOf(1,2,3,4,5)
val data =?!
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);
like image 611
ALMIStack Avatar asked Oct 15 '22 16:10

ALMIStack


1 Answers

The 'ByteArray" representation of an IntArray can be calculated like this:

 fun IntArray.toByteArray(): ByteArray {

    val result = ByteArray(this.size * 4)

        for ((idx, value) in this.withIndex()) {
            result[idx + 3] = (value and 0xFF).toByte()
            result[idx + 2] = ((value ushr 8) and 0xFF).toByte()
            result[idx + 1] = ((value ushr 16) and 0xFF).toByte()
            result[idx] = ((value ushr 24) and 0xFF).toByte()
        }

        return result
    }

This result can then be Base64 encoded like mentioned in the question:

val vec = intArrayOf(1,2,3,4,5)
val data = vec.toByteArray()
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);
like image 118
Alexander Egger Avatar answered Oct 21 '22 04:10

Alexander Egger