Skip to content

Instantly share code, notes, and snippets.

@sergeyprokudin
Created January 6, 2019 14:50
Show Gist options
  • Save sergeyprokudin/4be24ca57a39e93b9da930604909d70c to your computer and use it in GitHub Desktop.
Save sergeyprokudin/4be24ca57a39e93b9da930604909d70c to your computer and use it in GitHub Desktop.
Bitwise operations: set clear bits, check set bits
def set_bit(x, i):
bi = 0b1 << i
return x | bi
def xor_bit(x, i):
bi = 0b1 << i
return x ^ bi
def clear_bit(x, i):
bi = ~(0b1 << i)
return x & bi
# more on topic: https://stackoverflow.com/questions/8898807/pythonic-way-to-iterate-over-bits-of-integer
def check_bits_set(x):
bit = 1
bits = []
while x >= bit:
if x & bit:
bits.append(bit)
bit <<= 1
return bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment