Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 55

Python Exercise Example 55

Python 100 Examples Python 100 Examples

**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

print

(

'The inverted result of variable a is: %d'

% b

)

print

(

'The inverted result of variable c is: %d'

% d

)

The output of the above example is:

变量 a 取反结果为: -8
变量 c 取反结果为: 6

Explanation:

Python 100 Examples Python 100 Examples