As seen another question in 0xFF0000FF An integer literal does not conform to the expected type kotlin.Int

I declaring value 0xFF as Byte

val b:Byte = 0xFF

接收The integer literal does not conform to the expected type Byte编译错误

因为我有kotlin.Byte条线索is signed byte

How to declaring Byte in Kotlin with 0x00 - 0xFF unsigned byte just like Byte b = 0xFF ?

.

.

如果您想要即时编译器进行测试并回答:

rextester , try.kotlinlang.org

推荐答案

Kotlin doesn't automatically convert between number types.

如果执行val b:Byte = 0xFF.toByte(),那么它将编译并生成一个值为-1的字节.

If you want to hold the unsigned byte value then you need to store it as a Char, but you will need to convert it to another type to print it as a number:

val b = 0xFF.toChar()
println(b.toInt())

Kotlin相关问答推荐

Kotlin -通过反射获得KProperty 1和CallableReference的实例

Compose:LaunchedEffect在密钥更改后不会重新启动

Kotlin协程挂起继续线程

Kotlin 海峡没有结束

使用 Kotlin 的 Springboot 中缺少 ResponseEntity 正文属性

Kotlin 接口类型参数

为什么这两个 Kotlin 协程函数不一样?

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

匹配在单词边界上包含特殊字符的变量字符串的正则表达式

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

如何在 kotlin @Parcelize 中使用 null

interface扩展

如何禁用智能投射突出显示 Kotlin?

Kotlin 顶级函数与对象函数

未找到导入 kotlinx.coroutines.flow.*

ObjectAnimator.ofFloat 不能直接在kotlin中取Int作为参数

Kotlin协程无法处理异常

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

在 Kotlin 中返回函数有不那么丑陋的方法吗?

如何在伴随对象中使用泛型