How to convert hex code to standard character in Kotlin

85 Views Asked by At

I have a string "Build \x26 sell" and I need to somehow replace this specific one "&" or any other hex codes into standard character. Is there any simple function for this? Thanks

2

There are 2 best solutions below

2
Romario On

You can create your own function :)

fun hexToAscii(hexStr: String): String {

    val startOfHex = hexStr.indexOf("\\x")
    val substring = hexStr.substring(startOfHex, startOfHex + 4)
    val regString = substring.substring(2, 4).toInt(16).toChar().toString()
    val res = hexStr.replaceFirst(substring, regString, false)
    if (res.contains("\\x")) {
        return hexToAscii(res)
    }
    return res
}
0
k314159 On

You can use replace with a lambda:

fun String.transformHexSequences() = replace("\\\\x[0-9a-fA-F]{2}".toRegex()) {
    it.value.substring(2).toInt(16).toChar().toString()
}

val str = "Build \\x26 sell"
println(str.transformHexSequences()) // "Build & sell"

Note, however, that Char type can represent higher values than 2 hex digits can represent. If your source string has the possibility to contain such higher values, amend the above as necessary.