Thursday, 16 March 2017

Python Operators: Bit-wise Operators

Bit-wise Operators:

  • Bit-wise operators are used to converts the operands data in the form of  Binary format and performs the operations on the Binary data(1 and 0), here 1 means True,0 means False.
  • Bit-wise operators act on operands as if they were string of binary digits. It operates bit by bit.
  • Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)



Example1: Bit-wise AND( & )

x=10
y=4
print(bin(x))
print(bin(y))
print(x&y)
print(bin(x&y))

Output:

0b1010
0b100

0
0b0

Truth Tabel for AND

x=0
y=0
print(x&y)
x=0
y=1
print(x&y)
x=1
y=0
print(x&y)
x=1
y=1
print(x&y)

Output:

0
0
0
1

Example2: Bit-wise OR ( | )

x=10
y=4
print(bin(x))
print(bin(y))
print(x|y)
print(bin(x|y))

Output:

0b1010
0b100

14
0b1110

Truth Tabel for OR

x=0
y=0
print(x|y)
x=0
y=1
print(x|y)
x=1
y=0
print(x|y)
x=1
y=1
print(x|y)

Output:

0
1
1
1

Example3: Bit-wise NOT( ~ )

x=10
print(x)
print(bin(x))
print(~x)

Output:

10
0b1010

-11
-0b1011
Note:
 calculate the ~x value. 

Example4: Bit-wise XOR( ^ )

x=10
y=4
print(bin(x))
print(bin(y))
print(x^y)
print(bin(x^y))

Output:

0b1010
0b100

14
0b1110

Truth Tabel for XOR:

x=0
y=0
print(x^y)
x=0
y=1
print(x^y)
x=1
y=0
print(x^y)
x=1
y=1
print(x^y)

Output:

0
1
1
0

Example4: Bit-wise  Right-Shift ( >> )

x=10
print(x)
print(bin(x))
print(x>>2)
print(bin(x>>2))

Output:

10
0b1010

2
0b10

Explanation:
Example4: Bit-wise  Left-Shift ( << )

x=10
print(x)
print(bin(x))
print(x<<2)
print(bin(x<<2))

Output:

10
0b1010

40
0b101000

Explanation:


No comments:

Post a Comment