我在帶有 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()
}
uj5u.com熱心網友回復:
你快到了。您只需要將 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://www.uj5u.com/ruanti/454458.html
上一篇:在文本框中插入一個數字時出錯
