我正在尝试使用按位非运算符 ~
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
应该打印出 00001111
( docs ),但它打印出 -11110001
。这是怎么回事?
最佳答案
这不是按位运算符的问题,而是 String
初始化程序的行为问题。
String
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"
关于ios - Swift 2 NOT 按位运算不按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32343290/