如何在 KOTLIN 中将十六进制字符串转换为 ASCII 字符串
how to convert Hex String to ASCII String in KOTLIN
我在使用 BLE 模块的应用程序中收到一个六角形字符串
Hex string
0031302D31300D0A
这个字符串在ASCII中是10-10\r\n(表示x轴坐标和y 轴)。
我尝试使用 toCharArray 函数转换为数组中的 ASCII,并有可能解析字符串并获取 x 和 y 值,但它 returns logcat [C@ 中的这样一个字符串3cea859
我也尝试创建一个函数,但它returns相同类型的字符串
fun String.decodeHex(): ByteArray{
check(length % 2 == 0){"Must have an even length"}
return chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
}
你快到了。您只需要将 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
更合适。)
我在使用 BLE 模块的应用程序中收到一个六角形字符串 Hex string
0031302D31300D0A
这个字符串在ASCII中是10-10\r\n(表示x轴坐标和y 轴)。 我尝试使用 toCharArray 函数转换为数组中的 ASCII,并有可能解析字符串并获取 x 和 y 值,但它 returns logcat [C@ 中的这样一个字符串3cea859
我也尝试创建一个函数,但它returns相同类型的字符串
fun String.decodeHex(): ByteArray{
check(length % 2 == 0){"Must have an even length"}
return chunked(2)
.map { it.toInt(16).toByte() }
.toByteArray()
}
你快到了。您只需要将 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
更合适。)