如何在 Kotlin 中对 IntArray 进行 Base64 编码

ALM*_*ack 7 base64 kotlin

如何intArrayOf使用 Kotlin 对 buff 进行 Base64 编码。

val vec = intArrayOf(1,2,3,4,5)
val data =?!
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)

Ale*_*ger 4

an 的“ByteArray”表示IntArray可以这样计算:

 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
    }
Run Code Online (Sandbox Code Playgroud)

然后可以像问题中提到的那样对该结果进行 Base64 编码:

val vec = intArrayOf(1,2,3,4,5)
val data = vec.toByteArray()
val base64Encoded = Base64.encodeToString(data, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)