Home > database >  how to convert Hex String to ASCII String in KOTLIN
how to convert Hex String to ASCII String in KOTLIN

Time:03-31

I receive on my application with a BLE module a hexagonal String Hex string

0031302D31300D0A

This string in ASCII is 10-10\r\n (which represents the coordinates of the x axis and the y axis). I tried to use the toCharArray function to convert to ASCII in an array and have the possibility to parse the string and get the x and y values but it returns a string like this in the logcat [C@3cea859

I also tried to create a function but it returns the same type of string

fun String.decodeHex(): ByteArray{
        check(length % 2 == 0){"Must have an even length"}
        return chunked(2)
            .map { it.toInt(16).toByte() }
            .toByteArray()
    }

CodePudding user response:

You're nearly there. You just need to convert the ByteArray to a String. The standard toString() method comes from type Any (equivalent to Java's Object). The ByteArray doesn't override it to give you what you want. Instead, use the String constructor:

fun String.decodeHex(): String {
    require(length % 2 == 0) {"Must have an even length"}
    return String(
        chunked(2)
            .map { it.toInt(16).toByte() }
            .toByteArray()
    )
}

(Note also that require is more appropriate than check in that context.)

  • Related