Python – Bitwise Operators

Bitwise operators are used to perform operations on binary numbers.

d = 5  # 101 in binary
e = 3  # 011 in binary
print(d & e)  # Output: 1 (001 in binary)

OR (|): Sets each bit to 1 if one of two bits is 1.

print(d | e)  # Output: 7 (111 in binary)

XOR (^): Sets each bit to 1 if only one of two bits is 1.

print(d ^ e)  # Output: 6 (110 in binary)

NOT (~): Inverts all the bits.

print(~d)  # Output: -6 (In binary: 101 becomes 010, which is -6 in two's complement form)

Left Shift (<<): Shifts bits to the left by the specified number of positions.

print(d << 1)  # Output: 10 (101 becomes 1010)

Right Shift (>>): Shifts bits to the right by the specified number of positions.

print(d >> 1)  # Output: 2 (101 becomes 010)

Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com