swift 中的位和算术运算

Bitwise and arithmetic operations in swift

老实说,移植到 swift3(从 obj-c)很困难。最简单但最快的问题。

public func readByte() -> UInt8
{
    // ...
}

public func readShortInteger() -> Int16
{
    return (self.readByte() << 8) + self.readByte();
}

从编译器获取错误消息:"Binary operator + cannot be applied to two UInt8 operands."

怎么了?

ps。真可惜 ;)

readByte return一个UInt8所以:

  1. 你不能将 UInt8 左移 8 位,你会丢失它的所有位。
  2. 表达式的类型是 UInt8,不适合它正在计算的 Int16 值。
  3. 表达式的类型是 UInt8,不是注释的 return 类型 Int16

d

func readShortInteger() -> Int16
{
    let highByte = self.readByte()
    let lowByte = self.readByte()

    return Int16(highByte) << 8 | Int16(lowByte)
}

虽然 Swift 对操作数有严格的左右评估顺序,但我重构了代码以明确首先读取哪个字节,然后读取哪个字节。

此外,OR 运算符更加自文档化和语义化。

Apple 在此处提供了一些很棒的 Swift 文档:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html

let shiftBits: UInt8 = 4   // 00000100 in binary
shiftBits << 1             // 00001000
shiftBits << 2             // 00010000
shiftBits << 5             // 10000000
shiftBits << 6             // 00000000
shiftBits >> 2             // 00000001