令人惊讶的是(对我来说),这段代码并没有达到我的目的:

fun ByteArray.toHexString() : String {
    return this.joinToString("") { it.toString(16) }
}

结果是Bytesigned,所以您得到了单个字节的负祸不单行表示,这导致了一个完全虚假的最终结果.

Also, Byte.toString won't pad leading zeroes, which you'd want here.

最简单的(没有附加库,理想情况下没有扩展)resp是什么.最有效的解决方案?

推荐答案

As I am on Kotlin 1.3 you may also be interested in the UByte soon (note that it's an experimental feature. See also Kotlin 1.3M1 and 1.3M2 announcement)

E.g.:

@ExperimentalUnsignedTypes // just to make it clear that the experimental unsigned types are used
fun ByteArray.toHexString() = asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') }

格式化选项可能是其他变体中最好的(但可能不那么容易阅读……而且我总是忘了它是怎么工作的,所以肯定不容易记住(对我来说:-):

fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }

Kotlin相关问答推荐

如何在Jetpack Compose中从领域查询中读取数据?

如何使用multiset与JOOQ获取关联的记录列表?

在 map 中查找键与在 kotlin 中查找 firstOrNull

Kotlin 函数中接收者和参数的类型相同

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

为空数组添加值

模拟异常 - 没有找到答案

Kotlin boxed Int 不一样

Kotlin:使用Gradle进行增量编译

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

使用 Kotlin 创建自定义 Dagger 2 范围

以Kotlin为单位的货币数据类型

Kotlin out-projected 类型禁止使用

使用 rxbinding 时我应该取消订阅吗?

WebFlux 功能:如何检测空 Flux 并返回 404?

lateinit 的 isInitialized 属性在伴随对象中不起作用

内联 Kotlin 方法没有覆盖报告

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用

Kotlin for assertThat(foo, instanceOf(Bar.class))

如何在 kotlin 中创建重复对象数组?