Swift 2 NOT 按位运算未按预期运行

Kev*_*vin 1 bitwise-operators ios swift swift-playground swift2

我正在尝试使用按位非运算符在 Swift 中翻转数字的所有位 ~

func binary(int: Int) -> String {
    return String(int, radix: 2)
}

let num = 0b11110000
binary(num) //prints "11110000"

let notNum = ~num
binary(notNum) //prints "-11110001"
Run Code Online (Sandbox Code Playgroud)

我的理解是notNum应该打印出00001111( docs ) 而不是打印出来-11110001。这里发生了什么?

rin*_*aro 5

这不是按位运算符的问题,而是String初始化程序的行为问题。有2个init(_:radix:uppercase:)初始化程序String

public init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
public init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
Run Code Online (Sandbox Code Playgroud)

要获得预期结果,您必须使用UnsignedIntegerType一个:

let num:UInt = 0b11110000
let notNum = ~num

String(notNum, radix: 2)
// -> "1111111111111111111111111111111111111111111111111111111100001111"
Run Code Online (Sandbox Code Playgroud)

或者:

let num = 0b11110000
let notNum = ~num

String(UInt(bitPattern: notNum), radix: 2)
// -> "1111111111111111111111111111111111111111111111111111111100001111"
Run Code Online (Sandbox Code Playgroud)