有没有比下面的版本更好/更短的方法从常量十六进制创建字节数组?

byteArrayOf(0xA1.toByte(), 0x2E.toByte(), 0x38.toByte(), 0xD4.toByte(), 0x89.toByte(), 0xC3.toByte())

I tried to put 0xA1 without .toByte() but I receive syntax error complaint saying integer literal does not conform to the expected type Byte. Putting integer is fine but I prefer in hex form since my source is in hex string. Any hints would be greatly appreciated. Thanks!

推荐答案

作为一个选项,您可以创建简单的函数

fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() }

and use it

val arr = byteArrayOfInts(0xA1, 0x2E, 0x38, 0xD4, 0x89, 0xC3)

Kotlin相关问答推荐

判断字符串是否除了.&" ",","@""""

Kotlin中的增广赋值语句中的难以理解的错误

在Mapstruct中重用@映射定义

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

Kotlin - 协程未按预期执行

高效匹配两个 Flux

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

为 Gradle 子项目配置 Kotlin 扩展

在 Kotlin 中,::class.simpleName是做什么的?

如何从kotlin中的ArrayList中删除所有元素

.indices 在 kotlin 中的含义是什么?

比较 Kotlin 中的可比对象列表

找不到 androidsdk.modules

在Kotlin中不带类直接引用枚举实例

Kotlin的web-framework框架

Android 与 Kotlin - 如何使用 HttpUrlConnection

使用Dagger 2提供函数依赖性

IllegalStateException:function = , count = 3, index = 3

旋转 kotlin 数组

Kotlin - 为什么我会得到 KotlinNullPointerException