Skip to content

Instantly share code, notes, and snippets.

@Harduim
Created July 1, 2022 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harduim/412bd00c8a3d764831f143b04ef5beab to your computer and use it in GitHub Desktop.
Save Harduim/412bd00c8a3d764831f143b04ef5beab to your computer and use it in GitHub Desktop.
LSB using python, naive implementation vs bitwise black magic.
flags_bytes = ["00000000", "00000001", "00000110", "00000011", "01001100", "10001000"]
flags = [0, 1, 6, 3, 76, 136]
lsb_expected = [0, 1, 2, 1, 4, 8]
def naive_lsb(num):
for i, bit in enumerate(bin(num)[2:][::-1]):
if int(bit) == 1:
return 2**i
return 0
def proper_lsb(num):
return num & -num
naive_result = [naive_lsb(lb) for lb in flags]
assert lsb_expected == naive_result, f"{lsb_expected} !== {naive_result}"
proper_result = [proper_lsb(lb) for lb in flags]
assert lsb_expected == proper_result, f"{lsb_expected} !== {proper_result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment