Swift NOT 运算符 (~) 打印出与使用时不同的值
Swift NOT operator (~) prints different values than when used
Swift 按位非运算符 (~) 反转数字中的所有位。
文档提供了示例:
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
我可以通过打印字符串来确认这一点:
print(String(invertedBits, radix: 2)) // equals 11110000
鉴于此逻辑,我预计 ~0 to equal 1
和 ~1 to equal 0
。然而,像我上面那样打印这些打印出一些意想不到的东西:
print(String(~0b1, radix: 2)) // equals -10
print(String(~0b0, radix: 2)) // equals -1
在使用时我看到了一些不同的东西:
print(String(0b100 & ~0b111, radix: 2)) // equals 0 just as I would expect 100 & 000 to equal 000
但是
print(String(~0b111, radix: 2)) // equals -1000
~0b111
看起来好像是 0b000
但它打印为 -1000
这是怎么回事?
在文档提供的示例中,initialBits
具有显式类型。可以通过以下代码显示正在发生的事情
let number = 0b1 // we don't specify a type, therefore it's inferred
print(type(of: number)) // Int
print(String(~number, radix: 2)) // -10 as you know
print(number.bitWidth) // 64 because integers have 64 bits
// now if we create a 64 bit number, we can see what happened
// prints -10 because this number is equivalent to the initial number
print(String(~0b0000000000000000000000000000000000000000000000000000000000000001, radix: 2))
Swift 按位非运算符 (~) 反转数字中的所有位。
文档提供了示例:
let initialBits: UInt8 = 0b00001111 let invertedBits = ~initialBits // equals 11110000
我可以通过打印字符串来确认这一点:
print(String(invertedBits, radix: 2)) // equals 11110000
鉴于此逻辑,我预计 ~0 to equal 1
和 ~1 to equal 0
。然而,像我上面那样打印这些打印出一些意想不到的东西:
print(String(~0b1, radix: 2)) // equals -10
print(String(~0b0, radix: 2)) // equals -1
在使用时我看到了一些不同的东西:
print(String(0b100 & ~0b111, radix: 2)) // equals 0 just as I would expect 100 & 000 to equal 000
但是
print(String(~0b111, radix: 2)) // equals -1000
~0b111
看起来好像是 0b000
但它打印为 -1000
这是怎么回事?
在文档提供的示例中,initialBits
具有显式类型。可以通过以下代码显示正在发生的事情
let number = 0b1 // we don't specify a type, therefore it's inferred
print(type(of: number)) // Int
print(String(~number, radix: 2)) // -10 as you know
print(number.bitWidth) // 64 because integers have 64 bits
// now if we create a 64 bit number, we can see what happened
// prints -10 because this number is equivalent to the initial number
print(String(~0b0000000000000000000000000000000000000000000000000000000000000001, radix: 2))