Skip to content

Instantly share code, notes, and snippets.

@kalebr
Created June 20, 2014 17:56
Show Gist options
  • Save kalebr/eb79b3f28c09ff732902 to your computer and use it in GitHub Desktop.
Save kalebr/eb79b3f28c09ff732902 to your computer and use it in GitHub Desktop.
Encoding a selection of sets into an int and decoding.
def make_id( v, bit_map ):
bits_used = 0
_id = 0
for pair in zip( v, bit_map ):
_id += pair[0] * (2 ** bits_used )
bits_used += pair[1]
return _id
def unmake_id( vid, bit_map ):
total_bits = 0
remainder = []
for b in bit_map:
total_bits += b
a = ( ( vid - sum( remainder ) ) % ( 2 ** total_bits ) ) / ( 2 ** ( total_bits - b ) )
remainder.append( a )
return remainder
def make_bit_map( max_values ):
bit_map = []
for v in max_values:
i = 1
while 2 ** i < v - 1:
i += 1
bit_map.append( i )
return bit_map
maxs = [ 16, 8, 8, 22, 16]
values = [15, 3, 0, 1, 14]
print '{:<20}'.format( 'max values per slot' ),
for m in maxs:
print '{:>4}'.format(m),
print
bits = make_bit_map( maxs )
print '{:<20}'.format( 'num bits per slot' ),
for b in bits:
print '{:>4}'.format(b),
print
print '{:<20}'.format( 'original values' ),
for v in values:
print '{:>4}'.format( v ),
print
print
set_id = make_id( values, bits )
print '{:<22}'.format( 'encoded value' ),
print '{}'.format( set_id )
print '{:<20}'.format( 'decoded value' ),
for v in unmake_id( set_id, bits ):
print '{:>4}'.format( v ),
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment