详细介绍Python语言中的按位运算符

WBOY
Release: 2016-06-06 11:28:16
Original
1956 people have browsed it

按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:

按位与   ( bitwise and of x and y )

  &  举例: 5&3 = 1  解释: 101  11 相同位仅为个位1 ,故结果为 1

按位或   ( bitwise or of x and y )

  |  举例: 5|3 = 7  解释: 101  11 出现1的位是 1 1 1,故结果为 111

按位异或 ( bitwise exclusive or of x and y )

  ^  举例: 5^3 = 6  解释: 101  11 对位相加(不进位)是 1 1 0,故结果为 110

按位反转 (the bits of x inverted )

  ~  举例: ~5 = -6  解释: 将二进制数+1之后乘以-1,即~x = -(x+1),-(101 + 1) = -110

    按位反转仅能用在数字前面。所以写成 3+~5 可以得到结果-3,写成3~5就出错了

按位左移 ( x shifted left by n bits )

 

按位右移 ( x shifted right by n bits )

  >> 举例: 5>>2 = 1  解释:101 向右移动2位得到 1,即去掉右面的2位

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template