Created
April 11, 2022 21:10
-
-
Save jonashaag/6d98df6bdc5617a1a1d2a760adb37a33 to your computer and use it in GitHub Desktop.
Python int12
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 pack(arr): | |
"""Pack integers < 2**12 into 12 bit integers, encoded as bytes""" | |
out = [] | |
for i in range(0, len(arr), 2): | |
e1, e2 = arr[i:i+2] | |
assert 0 <= e1 < 2**12 | |
assert 0 <= e2 < 2**12 | |
e1 = (e1 << 4) | (e2 >> 8) | |
e2 &= 2**8-1 | |
assert e1 <= 2**16-1 | |
out.extend([e1 >> 8, e1 & 2**8-1, e2]) | |
return out | |
def unpack(arr): | |
"""Unpack 12 bit integers, encoded as bytes.""" | |
out = [] | |
for i in range(0, len(arr), 3): | |
e1, e2, e3 = arr[i:i+3] | |
assert 0 <= e1 < 2**8 | |
assert 0 <= e2 < 2**8 | |
assert 0 <= e2 < 2**8 | |
n1 = e1 << 4 | e2 >> 4 | |
n2 = (e2 & 0xf) << 8 | e3 | |
out.extend([n1, n2]) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment