Bitwise Operators in Python
& | ^ ~ << >> work on the binary representation of integers.
Easy
reg = 0b1010_0000
reg |= 1 << 3 # set bit 3
reg &= ~(1 << 7) # clear bit 7
bool(reg & (1 << 5)) # test bit 5
bin(reg), hex(reg)
Python integers have unlimited size, so ~x is -x - 1; mask with & 0xFF to emulate fixed-width registers.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.