Last active
February 25, 2024 15:59
-
-
Save TorsteinOvstedal/66b3dfda93a62b896450abddaa5a3126 to your computer and use it in GitHub Desktop.
Iterate through blocks of bits from a number using python generator.
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 bitstream(x: int, length: int, block_size: int): | |
assert length > 0 and block_size > 0, "Unsupported parameters" | |
mask = int("1" * block_size, 2) | |
for i in range(length): | |
block = x & mask | |
x >>= block_size | |
yield block | |
# Example usage | |
if __name__ == "__main__": | |
x = 0b1101_1111_1010_0001 | |
bits = bitstream(x, 4, 4) | |
for block in bits: | |
print(f"{block:>04b}") | |
# Output | |
# | |
# 0001 | |
# 1010 | |
# 1111 | |
# 1101 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment