ios - Swift 2 NOT 按位运算不按预期运行

标签 ios swift swift2 bitwise-operators swift-playground

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

在 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 应该打印出 00001111 ( docs ),但它打印出 -11110001。这是怎么回事?

最佳答案

这不是按位运算符的问题,而是 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"

关于ios - Swift 2 NOT 按位运算不按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32343290/

相关文章:

ios - 在后台模式下运行网络连接

iOS 10 - 模糊背景不再起作用

ios - NSDate 到具有时区偏移量的字符串

swift - UITextView 更改特定文本的文本颜色

javascript - 如何使用相应的 native 应用程序从移动网站打开链接

iphone - Cordova/Phonegap iPhone 闪屏错误

python - 是否有 Swift 等同于 Python 中的 'Filter' 函数?

ios - WKWebView 仅垂直滚动而不是水平滚动而不是页面缩放

ios - Swift:在新行将字符串拆分为数组 - 基于 Windows 的文本

ios - IBOutlet 为零,但在 Storyboard 中已连接(Swift 2)