kotlin 十六进制文本(String)和字节集(ByteArray)互转

February 23, 2021 · 开发笔记 · 216次阅读
object HexUtils {
    fun hexStringToBytes(hexString: String?): ByteArray? {
        @Suppress("NAME_SHADOWING")
        var hexString = hexString
        if (hexString == null || hexString == "") {
            return null
        }
        hexString = hexString.toUpperCase()
        val length = hexString.length / 2
        val hexChars = hexString.toCharArray()
        val data = ByteArray(length)
        for (i in 0 until length) {
            val pos = i * 2
            data[i] = (charToByte(hexChars[pos]).toInt() shl 4 or charToByte(hexChars[pos + 1]).toInt()).toByte()
        }
        return data
    }

    fun bytesToHexString(src: ByteArray?): String? {
        val stringBuilder = StringBuilder("")
        if (src == null || src.isEmpty()) {
            return null
        }
        for (element in src) {
            val v = element.toInt() and 0xFF
            val hv = Integer.toHexString(v)
            if (hv.length < 2) {
                stringBuilder.append(0)
            }
            stringBuilder.append(hv)
        }
        return stringBuilder.toString()
    }

    private fun charToByte(c: Char): Byte {
        return "0123456789ABCDEF".indexOf(c).toByte()
    }
}

除声明外inSoraSky博客(http://www.sorasky.in/)所有内容均为本人所原创,转载时请注明来源!

喝杯水

KotlinAndroid十六进制文本

最后编辑于4个月前

添加新评论