1

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()
    }
4
  • String hex = "0031302D31300D0A"; Please tell what x and y would be. String xhex = ... String yhex = .... Commented Mar 30, 2022 at 8:24
  • @blackapps xhex = 3130, separatorHex = 2D, yhex = 3130 endCharacHex = 0D0A Commented Mar 30, 2022 at 8:44
  • You mean xhex = "3130". A string. If you dont have a string at start (like i used in my comment) but a byte array of 8 bytes then please state so in your post. Commented Mar 30, 2022 at 10:22
  • yes @blackapps i mean xhex = "3130", separatorHex = "2D", yhex = "3130" endCharacHex = "0D0A" Commented Mar 30, 2022 at 11:48

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

13 Comments

Hey, I convert the byte array to a string with the toString function and get nothing on logcat. fun String.decodeHex(): String{ require(length % 2 == 0){"Must have an even length"} return String(chunked(2) .map { it.toInt(16).toByte() } .toByteArray()) } // output : nothing
Are you actually calling it? Something like log(hexString.decodeHex())?
@P.C You can see it working here: pl.kotl.in/xMdOUuqfG
@P.C one possible issue is that the string starts with hex 00 which results in a '\0' character at the beginning of the string, which maybe the logger doesn't like.
Yes i call it Log.i("sensor", hexstring.decodHex()) and the only thing I have is this 2022-03-30 11:22:56.397 2016-2016/com.example.lightrdetect D/sensor:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.