它在Kotlinfor &+和Swift中的等价物是什么

mnemlml8  于 2023-06-28  发布在  Swift
关注(0)|答案(4)|浏览(144)

这是Swift代码中的一行,我想在Kotlin中使用:

  1. // var hash: UInt32 = 0
  2. hash = hash &+ UInt32(bytes[i])

它是按位添加数字,然后忽略溢出。
请参阅Swift语言文档中的“值溢出”:(https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
但是,当您特别希望溢出条件截断可用位数时,您可以选择加入此行为,而不是触发错误。Swift提供了三个算术溢出运算符,它们可以选择整数计算的溢出行为。这些运算符都以&开头(&):

  • 溢出添加(&+
  • 溢流减影(&-
  • 溢出乘法(&*

Kotlin中的等价物是什么?我在官方文件里没看到。

k3bvogb1

k3bvogb11#

Kotlin不会在整数溢出时引发错误。Kotlin基于JVM,所以它也没有unsigned类型。所以你可以简单地添加这些值:

  1. val hash : Int = ...
  2. val bytes : ByteArray = ...
  3. hash += bytes[i]

当然,Byte也是在Kotlin中签名的,所以在扩展它时可能需要进行值转换:

  1. val byte : Byte = bytes[i]
  2. val byteAsInt : Int = byte.toInt()
  3. if (byteAsInt < 0) byteAsInt = 255 + byteAsInt + 1
  4. hash += byteAsInt
c3frrgcw

c3frrgcw2#

没有像这样的操作符,但Kotlin可以做同样的事情:

  1. val a: Byte = 100
  2. val b: Byte = 121
  3. val x: Byte = (((a + b) shl 8) shr 8).toByte()
  4. println(x)

因此可以创建操作符:

  1. infix fun Byte.`&+`(b: Byte): Byte = (((this + b) shl 8) shr 8).toByte()

然后这样使用:

  1. val a: Byte = 100
  2. val b: Byte = 121
  3. val x: Byte = a `&+` b
  4. println(x)
展开查看全部
qf9go6mv

qf9go6mv3#

我计划使用我的Kotlin文件中的以下java代码:

  1. public static byte addBytesWithOverflow(byte a, byte b) {
  2. int val = (a + b) & 0xFF;
  3. return (byte) val;
  4. }
bt1cpqcv

bt1cpqcv4#

在我尝试了这么长时间之后,这对我很有效,我试图在与iOS hash =(hash << 5)&+ hash &+ Int(char.asciiValue!)

  1. fun String.djb2() : Long {
  2. var hash : Long = 5381
  3. for (char in this) {
  4. val code = char.toInt()
  5. hash = ((hash shl 5) + hash+code).toLong()
  6. }
  7. return hash

}

相关问题