Created
March 16, 2012 00:26
-
-
Save jtauber/2047843 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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