看python官方说明学python-移位-bitewise

来源:互联网 发布:淘宝标题怎么写好 编辑:程序博客网 时间:2024/06/04 19:20

4.4.1. Bitwise Operations on Integer Types (数位操作)

Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value (this assumes a sufficiently large number of bits that no overflow occurs during the operation).

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).

This table lists the bitwise operations sorted in ascending priority (operations in the same box have the same priority):

OperationResultNotesx | ybitwise or of x and y x ^ ybitwise exclusive or of x and y x & ybitwise and of x and y x << nx shifted left by n bits(1)(2)x >> nx shifted right by n bits(1)(3)~xthe bits of x inverted 

说明——————————————————

将x转换成二进制,然后根据二进制转移位置。

x << n 

5 << 2

将十进制5转换成二进制"0b101"然后向左移动两位,并补零成为"0b10100", 再转换成十进制。20

于是输出的结果是20

可以这样验证: 在python命令行里面输入bin(20)得到的结果是'0b10100', 0b的意思是binary 二进制。

5 >> 2       将'0b101'向右移动两位(再不溢出的情况下,就是说移动不超过其二进制长度),得到的结果是'0b1',十进制是1

于是输出1

x^y,  是x与y每一个位之间的  两个位都为真的时候为假取0,其他的位值不变然后返回 值

x&y,                                              两个位都为真的时候为真取1,所有值都这样,然后返回 值

x | y                                              两个位有一个为真,运算为真取1, 所有值都这样, 然后返回值 

这些指的是各位之间的关系,

——————————————————————

Notes:

  1. Negative shift counts are illegal and cause a ValueError to be raised.
  2. A left shift by n bits is equivalent to multiplication by pow(2, n) without overflow check.
  3. A right shift by n bits is equivalent to division by pow(2, n) without overflow check.
原创粉丝点击