当前位置: 代码迷 >> 综合 >> Python bitwise operator
  详细解决方案

Python bitwise operator

热度:14   发布时间:2024-01-11 02:52:30.0

bitwise

英 [b?t'wa?z]      美 [b?t'wa?z]    
  • n.逐位;按位

  1. However,you probably won't use the bitwise operators much.
    然而,也许不必过于频繁地进行按位运算。
  2. Is a numeric value representing the inclusive bitwise disjunction of two numeric bit patterns.
    是一个表示两个数位组合模式的包含按位析取的数值。

There are following Bitwise operators supported by Python language

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands  (a & b) (means 0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> = 15 (means 0000 1111)

Example

#!/usr/bin/pythona = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", cc = a | b;        # 61 = 0011 1101 
print "Line 2 - Value of c is ", cc = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", cc = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", cc = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", cc = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

When you execute the above program it produces the following result ?

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15