python bitwise and code example
Example 1: binary operation python
x << y
"left shifted x by y places"
x >> y
"right shift x by y places"
x & y
"bitwise and"
x | y
"bitwise or".
~ x
"Complement of x"
x ^ y
"bitwise exclusive or"
Example 2: python bitwise operators
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
Example 3: python bitwise operators methods
OPERATOR DESCRIPTION SYNTAX FUNCTION IN-PLACE METHOD
& Bitwise AND a & b and_(a, b) __and__(self, other)
| Bitwise OR a | b or_(a, b) __or__(self, other)
^ Bitwise XOR a ^ b xor(a, b) __xor__(self, other)
~ Bitwise NOT ~ a invert(a) __invert__(self)
<< Bitwise L shift a << b lshift(a, b) __lshift__(self, other)
>> Bitwise R shift a >> b rshift(a, b) __irshift__(self, other)
Example 4: bitwise operators python
OPERATOR DESCRIPTION SYNTAX
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Example 5: data = a &b python
a = 60
b = 13
c = 0
c = a & b;
print "Line 1 - Value of c is ", c
c = a | b;
print "Line 2 - Value of c is ", c
c = a ^ b;
print "Line 3 - Value of c is ", c
c = ~a;
print "Line 4 - Value of c is ", c
c = a << 2;
print "Line 5 - Value of c is ", c
c = a >> 2;
print "Line 6 - Value of c is ", c