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( ~ )
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:
No comments:
Post a Comment