Base16编/解码的Kotlin语言实现
1.1、Base16编码

Base16编码的Kotlin语言实现如下:

const val BASE_16_CHARACTER_UPPER_TABLE = "0123456789ABCDEF"
const val BASE_16_CHARACTER_LOWER_TABLE = "0123456789abcdef"

fun ByteArray.base16Encode(upperCase: Boolean = true): String {
    if (size == 0) return ""

    val result = StringBuilder(this.size * 2)
    for (byte in this) {
        val intValue = byte.toInt()
        //向右移动4bit,获得高4bit
        val highByte = intValue shr 4 and 0x0F
        //与0x0f做位与运算,获得低4bit
        val lowByte = intValue and 0x0F
        if (upperCase) {
            result.append(BASE_16_CHARACTER_UPPER_TABLE[highByte])
            result.append(BASE_16_CHARACTER_UPPER_TABLE[lowByte])
        } else {
            result.append(BASE_16_CHARACTER_LOWER_TABLE[highByte])
            result.append(BASE_16_CHARACTER_LOWER_TABLE[lowByte])
        }
    }
    return result.toString()
}

Kotlin语言中还可以使用如下简便方法实现Base16编码:

fun ByteArray.base16Encode2(upperCase: Boolean = true): String {
    val result = StringBuilder(size * 2)
    for (byte in this) { // 使用String的format方法进行转换
        result.append(String.format(if (upperCase) "%02X" else "%02x", byte.toInt() and 0xFF))
    }
    return result.toString()
}
1.2、Base16解码

Base16解码的Kotlin语言实现如下:

//把16进制字符转换成10进制表示的数字
fun Char.hex2dec(): Int = when (this) {
    in '0'..'9' -> this - '0'
    in 'a'..'f' -> this - 'a' + 10
    in 'A'..'F' -> this - 'A' + 10
    else -> -1
}

fun String.base16Decode(): ByteArray {
    val halfInputLength = length / 2
    val output = ByteArray(halfInputLength)
    for (i in 0 until halfInputLength) {
        //16进制数字转换为10进制数字的过程
        output[i] = (this[2 * i].hex2dec() * 16 + this[2 * i + 1].hex2dec()).toByte()
    }
    return output
}