在我的应用程序中,我收到了一个带有BLE模块的六角形字符串六角弦。
0031302D31300D0A
ASCII中的这个字符串是10-10\r\n (表示x轴和y轴的坐标)。我尝试使用toCharArray函数在数组中转换为ASCII,并有可能解析该字符串并获取x和y值,但它在logcat [C@3cea859 ]中返回如下字符串
我也尝试创建一个函数,但它返回相同类型的字符串。
fun String.decodeHex(): ByteArray{
check(length % 2 == 0){"Must have an even length"}
return chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
}发布于 2022-03-30 08:16:01
你就快到了。只需将ByteArray转换为字符串即可。标准的toString()方法来自于Any类型(相当于Java的Object)。ByteArray不会覆盖它来给你想要的。相反,使用String构造函数:
fun String.decodeHex(): String {
require(length % 2 == 0) {"Must have an even length"}
return String(
chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
)
}(还请注意,在这种情况下,require比check更合适。)
https://stackoverflow.com/questions/71673452
复制相似问题