0

我正在尝试将 BLE 本机字节处理助手转换为 Kotlin。在这个过程中,我注意到在

JAVA

myByteArray[offset] += (byte)(exponent & 0xFF);

它按预期工作,但是当转换为 kotlin KOTLIN

myByteArray[offset] += (exponent and 0x0F shl 4).toByte()

我收到了预期为整数的错误。所以我假设

"+="

是我的问题并导致假设为整数。所以我有两个问题。

1) += 究竟对字节做了什么。我明白那个

b += 1

是等价的

b = (字节)(b + 1)

但是字节到底发生了什么。是否正在进行转换,或者它是否转换为 int,然后将值添加回字节?

2) Kotlin 中的等价物是什么,为什么它在 Kotlin 中失败。我也试过做

  myByteArray[offset] = myByteArray[offset] + (exponent and 0x0F shl 4).toByte()

作为记录,如果您好奇的话,这是将整数值转换为 32 位浮点数。不确定这是否有帮助。

如果您对此感兴趣,完整的代码是:

mantissa = intToSignedBits(mantissa, 12)
exponent = intToSignedBits(exponent, 4)
myByteArray[offset++] = (mantissa and 0xFF).toByte()
myByteArray[offset] = (mantissa shr 8 and 0x0F).toByte()
myByteArray[offset] += (exponent and 0x0F shl 4).toByte() //hates this line

注意*它说

这个

因为我把它写成一个 ByteArray 扩展,所以把它想象成 byteArray 本身。

它的 KOTLIN 版本(错误)

在此处输入图像描述

它的 JAVA 版本(无错误):

在此处输入图像描述

我想要的不仅仅是一个答案,但我会接受它,哈哈。我想更多地了解这里发生的事情,以便将来我也可以自己解决这个问题。提前感谢任何花时间解释和帮助的人。

同样,当我们讨论这个主题时;)。

  private int unsignedByteToInt(byte b) {
        return b & 0xFF;
   }

为什么这在 Java 中有效,但在 Kotlin 中失败。

   private fun unsignedByteToInt(b: Byte): Int {
        return b and 0xFF
   }

老实说,我已经厌倦了编写 Java 辅助类来处理字节,所以我试图找出 Kotlin 字节处理的习惯用法。"and" 似乎只有 Ints 的重载,并且字节在 Kotlin 中不被视为 Ints。

所以作为一个额外的问题,如果你能解释这个问题,我也会很感激。

4

2 回答 2

1

我相信你应该使用Byte#plus(Byte)

所以在你的情况下:

myByteArray[offset] = myByteArray[offset].plus((exponent and 0x0F shl 4).toByte())

.toByte()在这种情况下可能没有必要,因为plus()基本上需要任何数字,但我无法测试它。

于 2018-09-24T21:58:22.837 回答
1

您是否注意到分解您的陈述有效?

val newBytes = (myByteArray[offset]+(exponent and 0x0F shl 4)).toByte()
myByteArray[offset] = newBytes

这种行为的罪魁祸首是plus操作员签名。这些都是plusfor的重载Byte

/** Adds the other value to this value. */
public operator fun plus(other: Byte): Int
/** Adds the other value to this value. */
public operator fun plus(other: Short): Int
/** Adds the other value to this value. */
public operator fun plus(other: Int): Int
/** Adds the other value to this value. */
public operator fun plus(other: Long): Long
/** Adds the other value to this value. */
public operator fun plus(other: Float): Float
/** Adds the other value to this value. */
public operator fun plus(other: Double): Double

这些Byte都没有返回 a 并且没有 的重载plusAssign,因此它们是隐式创建的。

首先它执行plus(Byte)返回Int然后尝试分配,但它需要 aByte所以它会导致你的错误。

于 2018-09-24T22:03:39.117 回答