简体   繁体   中英

how to convert Hex String to ASCII String in KOTLIN

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()
    }

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 or the toString(Charset) function:

fun String.decodeHex(): String {
    require(length % 2 == 0) {"Must have an even length"}
    return chunked(2)
        .map { it.toInt(16).toByte() }
        .toByteArray()
        .toString(Charsets.ISO_8859_1)  // Or whichever encoding your input uses
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM