Skip to content

Instantly share code, notes, and snippets.

@jtauber
Created March 16, 2012 00:26
Show Gist options
  • Save jtauber/2047843 to your computer and use it in GitHub Desktop.
Save jtauber/2047843 to your computer and use it in GitHub Desktop.
def bitstruct(structure, value):
result = []
index = 8
for part in structure:
result.append((value & ((2 ** index - 1) - (2 ** (index - part) - 1))) >> (index - part))
index -= part
return tuple(result)
if __name__ == "__main__":
assert bitstruct((8, ), 42) == (42, )
assert bitstruct((1, ), 128) == (1, )
assert bitstruct((1, ), 64) == (0, )
assert bitstruct((1, 1), 64) == (0, 1)
assert bitstruct((4, 4), 127) == (7, 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment