与Swift中Kotlin for&+等效的是什么

时间:2018-07-13 22:11:34

标签: swift kotlin bitwise-operators

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

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

它是按位加数字,然后忽略溢出。

请参见Swift语言文档中的“值溢出”:(https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

  

但是,当您特别希望溢出条件截断可用位数时,可以选择采用这种行为,而不是触发错误。 Swift提供了三个算术溢出运算符,它们选择对整数计算进行溢出行为。这些运算符都以与号(&)开头:

     
      
  • 附加流量(&+
  •   
  • 溢出减法(&-
  •   
  • 溢出乘法(&*
  •   

它在Kotlin中的等效物是什么?我没有在官方文档中看到它。

3 个答案:

答案 0 :(得分:2)

在整数溢出的情况下,Kotlin不会引发错误。 Kotlin基于JVM,因此也不具有未签名的类型。因此,您只需添加值即可:

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

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

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

hash += byteAsInt

答案 1 :(得分:1)

没有像这样的运算符,但Kotlin可以这样做:

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

因此可以创建运算符:

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

并以此方式使用:

val a: Byte = 100
val b: Byte = 121
val x: Byte = a `&+` b
println(x)

答案 2 :(得分:0)

我计划使用我的kotlin文件中的以下Java代码:

public static byte addBytesWithOverflow(byte a, byte b) {
    int val = (a + b) & 0xFF;
    return (byte) val;
}