Skip to content

Instantly share code, notes, and snippets.

@theodoregoetz
Last active May 24, 2017 23:53
Show Gist options
  • Save theodoregoetz/55826af4e93442548f09c08e7766845d to your computer and use it in GitHub Desktop.
Save theodoregoetz/55826af4e93442548f09c08e7766845d to your computer and use it in GitHub Desktop.
bit-mask and shift bits individually to lowest position.
def accordion_shift(value, mask):
x = 0
to_bit = 0
for from_bit in range(len(bin(mask)) - 2):
if (1 << from_bit) & mask:
if (1 << from_bit) & value:
x |= 1 << to_bit
to_bit += 1
return x
accordion_shift(value=0b1100, mask=0b1101)
accordion_shift(value=0b100, mask=0b110)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment