Python Exercise Example 55
**Problem:** Learn to use the bitwise NOT ~.
Explanation:
Binary numbers are stored in memory in two's complement form.
Bitwise NOT: invert each bit of the binary number, 0 becomes 1 and 1 becomes 0.
The highest bit is the sign bit; it is 0 for positive numbers and 1 for negative numbers.
For positive numbers, the highest bit is 0 and the remaining bits represent the value itself (in binary); for example, the two's complement of +42 is 00101010.
For negative numbers, invert the bits of the two's complement of the number's absolute value, then add 1 to the whole number to obtain its two's complement. For example, the two's complement of -42 is 11010110 (00101010 with bits inverted
11010101+1 gives 11010110).
Calculation steps for ~9:
转二进制:0 1001
计算补码:0 1001
按位取反:1 0110
Convert to sign-magnitude form:
按位取反:1 1001
末位加 1:1 1010
符号位为 1 是负数,即 -10
Example
#!/usr/bin/python
-- coding: UTF-8 --
a
=
7
b
=
~
a
c
=
7
d
=
~
c
(
'The inverted result of variable a is: %d'
% b
)
(
'The inverted result of variable c is: %d'
% d
)
The output of the above example is:
变量 a 取反结果为: -8
变量 c 取反结果为: 6
Explanation:
-
~7, inverting 7: the two's complement of 7 is 00000111; inverting the complement gives 11111000. The highest bit 1 is the sign bit, indicating a negative number, so the integer corresponding to this complement is -8.
-
~-7 Inverting -7: the two's complement of -7 is 11111001; inverting the complement gives 00000110. The highest bit 0 is the sign bit, indicating a positive number, so the integer corresponding to the complement is 6.
Python 100 Examples