Last active
March 7, 2025 05:08
-
-
Save paretech/d03622d99de79794438f4669f41e1ff2 to your computer and use it in GitHub Desktop.
Collate Bytes by Nibble
This file contains hidden or 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
from collections.abc import Generator | |
def collate_nibbles(upper: bytes, lower: bytes) -> Generator[int]: | |
def to_nibbles(data: bytes) -> bytes: | |
"""Convert bytes to nibbles""" | |
return ( | |
nibble for byte in data for nibble in ((byte & 0xF0), (byte & 0x0F) << 4) | |
) | |
return ( | |
((upper_nibble) | (lower_nibble >> 4)) | |
for upper_nibble, lower_nibble in zip(to_nibbles(upper), to_nibbles(lower)) | |
) | |
if __name__ == "__main__": | |
upper = b"\xab\xab\xab\xab" | |
lower = b"\xcd\xcd\xcd\xcd" | |
# Alternate values (not as presentable) | |
# upper = b"\x01\x23\x45" | |
# lower = b"\xfe\xdc\xba\x98" | |
combined = bytes(collate_nibbles(upper, lower)) | |
# Combining upper (b'\xab\xab\xab\xab') and lower (b'\xcd\xcd\xcd\xcd') one | |
# nibble at a time results in combined (b'\xac\xbd\xac\xbd\xac\xbd\xac\xbd'). | |
print( | |
f"Combining upper ({upper}) and lower ({lower}) one " | |
f"nibble at a time results in combined ({combined})." | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment