Python Exercise Example 55

Python 100例Python 100 Examples

Topic:Learn to use the bitwise NOT operator ~.

Explanation:

Binary numbers are stored in memory in two's complement form.

Bitwise NOT: invert each bit of a binary number, 0 becomes 1, 1 becomes 0.

The most significant bit is the sign bit, with 0 for positive numbers and 1 for negative numbers.

For positive numbers, the most significant 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, take the two's complement of the absolute value, invert it bit by bit, then add 1 to the whole number to get the two's complement of that number. For example, the two's complement of -42 is 11010110 (00101010 inverted bit by bit

is 11010101, plus 1 gives 11010110).

Calculation steps for ~9:

转二进制:0 1001
计算补码:0 1001
按位取反:1 0110

Convert to the original code:

按位取反:1 1001  
末位加 1:1 1010
符号位为 1 是负数,即 -10

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

a = 7
b = ~a

c = -7
d = ~c

print ('The result of bitwise NOT on variable a is: %d' % b)
print ('The result of bitwise NOT on variable c is: %d' % d)

The output result of the above example is:

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

Explanation:

  • ~7, performing bitwise NOT on 7, the two's complement of 7 is 00000111, inverting the two's complement gives 11111000, the most significant bit 1 is the sign bit, indicating a negative number, so the integer corresponding to this two's complement is -8.

  • ~-7Performing bitwise NOT on -7, the two's complement of -7 is 11111001, inverting the two's complement gives 00000110, the most significant bit 0 is the sign bit, indicating a positive number, so the integer corresponding to this two's complement is 6.

Python 100例Python 100 Examples

Other Extensions