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

时间:2019-04-01 10:35:12

标签: kotlin base64

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

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

1 个答案:

答案 0 :(得分:0)

IntArray的'ByteArray'表示可以这样计算:

 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
    }

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

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