Swift 2 NOT 按位运算不符合预期

Swift 2 NOT bitwise operation does not behave as expected

我正在尝试使用按位非运算符 ~

翻转 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"

据我了解,notNum 应该打印出 00001111docs),但它却打印出 -11110001。这是怎么回事?

那是因为您使用的是 Int 而不是 UInt8:

这样试试:

func binary(uint8: UInt8) -> String {
    return String(uint8, radix: 2)
}

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

let notNum = ~num
binary(notNum) //prints "1111"

这不是按位运算符的问题,而是 String 初始化程序的行为问题。 String

中有2个init(_:radix:uppercase:)初始化器
public init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
public init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)

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

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

String(notNum, radix: 2)
// -> "1111111111111111111111111111111111111111111111111111111100001111"

或:

let num = 0b11110000
let notNum = ~num

String(UInt(bitPattern: notNum), radix: 2)
// -> "1111111111111111111111111111111111111111111111111111111100001111"