Skip to content

Instantly share code, notes, and snippets.

@lpereira
Created September 9, 2015 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpereira/9d95ee6caeacdaade299 to your computer and use it in GitHub Desktop.
Save lpereira/9d95ee6caeacdaade299 to your computer and use it in GitHub Desktop.
Value packing with prime numbers
#!/usr/bin/python
import math
def pack_bits(*bits):
n = 0
max_n = 1
for value, prime_for_value in bits:
while n % prime_for_value != value:
n += max_n
max_n *= prime_for_value
return n
def test(*values):
packed = pack_bits(*values)
bits = math.ceil(math.log(packed, 2)) or 1
print("Values: %s, packed: %d (%d bits)" % (values, packed, bits))
for value, prime in values:
assert(packed % prime == value)
if __name__ == '__main__':
test((1, 3), (4, 5), (3, 7))
test((2, 3), (4, 5), (3, 7))
test((2, 3), (4, 5), (6, 7))
test((2, 3), (1, 5), (3, 7))
test((2, 3), (2, 5), (3, 7))
test((2, 3), (3, 5), (3, 7))
test((2, 3), (4, 5), (3, 7))
test((2, 3), (4, 5), (4, 7))
test((2, 3), (4, 5), (5, 7))
test((2, 3), (4, 5), (6, 7))
test((1, 3), (1, 5), (1, 7))
test((0, 3), (1, 5), (0, 7))
test((1, 3), (2, 5), (3, 7), (10, 13))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment