Types 如何正确处理Kotlin中大于127的字节值?

Types 如何正确处理Kotlin中大于127的字节值?,types,type-conversion,kotlin,Types,Type Conversion,Kotlin,假设我有一个Kotlin程序,它有一个b类型的变量Byte,外部系统将大于127的值写入其中。“外部”意味着我不能更改它返回的值的类型 val a:Int=128 val b:Byte=a.toByte() a.toByte()和b.toInt()返回-128 假设我想从变量b中获得正确的值(128)。我怎么做 换句话说:magicallyExtractRightValue的什么实现将使以下测试运行 @Test fun testByteConversion() { val a:Int =

假设我有一个Kotlin程序,它有一个
b
类型的变量
Byte
,外部系统将大于
127
的值写入其中。“外部”意味着我不能更改它返回的值的类型

val a:Int=128
val b:Byte=a.toByte()

a.toByte()
b.toInt()
返回
-128

假设我想从变量
b
中获得正确的值(
128
)。我怎么做

换句话说:
magicallyExtractRightValue
的什么实现将使以下测试运行

@Test
fun testByteConversion() {
    val a:Int = 128
    val b:Byte = a.toByte()

    System.out.println(a.toByte())
    System.out.println(b.toInt())

    val c:Int = magicallyExtractRightValue(b)

    Assertions.assertThat(c).isEqualTo(128)
}

private fun magicallyExtractRightValue(b: Byte): Int {
    throw UnsupportedOperationException("not implemented")
}
更新1:建议的此解决方案似乎有效

private fun magicallyExtractRightValue(o: Byte): Int = when {
    (o.toInt() < 0) -> 255 + o.toInt() + 1
    else -> o.toInt()
}
private fun magicallyExtractRightValue(o:Byte):Int=when{
(o.toInt()<0)->255+o.toInt()+1
else->o.toInt()
}

使用Kotlin 1.3+您可以使用。e、 g.():

甚至要求直接使用
UByte
而不是
Byte
():

对于Kotlin 1.3之前的版本,我建议创建一个

用法示例:

val a: List<Int> = listOf(0, 1, 63, 127, 128, 244, 255)
println("from ints: $a")
val b: List<Byte> = a.map(Int::toByte)
println("to bytes: $b")
val c: List<Int> = b.map(Byte::toPositiveInt)
println("to positive ints: $c")

好老的
printf
符合我们的要求:

java.lang.String.format("%02x", byte)

byte
是用Java签名的,因此您必须接受它。为什么必须使用
字节
int
从哪里来?我有一个外部库,我不想更改它。它给我字节类型的值,其中包含负数。所以库已经给了你“-127”。为什么需要转换它?除非你在数字上使用它,否则它不会有什么不同。如果您确定该库实际上“意味着”128,那么您可以使用
short
int
(通过对负数执行255+b进行转换)。我需要实际的数值,因为在另一个第三方库中,该数值用作数组中的索引。数组索引是
int
。通过执行
intx=b<0,可以从“无符号字节”进行转换?255+b:b
EclipseKotlin插件不知何故不知道按位
,否则该怎么做?@Xerus我还没有真正使用eclipse插件,所以我不知道该说什么,但我怀疑有什么错误配置为
,并且
是“Kotlin stdlib”的一部分。您可以尝试将其用作非中缀:
toInt()。和(0xFF)
。为什么不将其烘焙到Kotlin??!?根据您的数据,这对
蓝牙gattcharacteristic
非常有用。谢谢。供参考。
fun Byte.toPositiveInt() = toInt() and 0xFF
val a: List<Int> = listOf(0, 1, 63, 127, 128, 244, 255)
println("from ints: $a")
val b: List<Byte> = a.map(Int::toByte)
println("to bytes: $b")
val c: List<Int> = b.map(Byte::toPositiveInt)
println("to positive ints: $c")
java.lang.String.format("%02x", byte)