How to store and write/load to/from file an arbitrary number of bits in Python? -


i want write hash function returning hash 3 integers a, b, c. want able choose number of bits each integer encoded , concatenate them. instance:

a=60  (8 bits) -> 00111100 b=113 (8 bits) -> 01110001 c=5   (4 bits) -> 0101 

should give

00111100011100010101 

i.e. 20 bits.

given a, b , c integers (60, 113 , 5) , number of bits allowed each (8, 8 , 4), how can hash, store in python object of total size (20 bits), , write/load file?

i think want. uses referenced bitio module write/read bits to/from file.

operating systems require files multiple of 8 bits in size, end creating 24-bit (3 byte) file store single 20-bit value. 16.7% of overhead per 20-bit value wouldn't occur, of course, if wrote several of them, 1 after another, , didn't call flush() until after last.

import bitio  # see http://stackoverflow.com/a/10691412/355230  # hash function configuration bw = 8, 8, 4  # bit widths of each integer hw = sum(bw)  # total bit width of hash  def myhash(a, b, c):     return (((((a & (2**bw[0]-1)) << bw[1]) |                 b & (2**bw[1]-1)) << bw[2]) |                 c & (2**bw[2]-1))  hashed = myhash(60, 113, 5) print '{:0{}b}'.format(hashed, hw)  # --> 00111100011100010101  open('test.bits', 'wb') outf:     bw = bitio.bitwriter(outf)     bw.writebits(hashed, hw)     bw.flush()  open('test.bits', 'rb') inf:     br = bitio.bitreader(inf)     val = br.readbits(hw)  print '{:0{}b}'.format(val, hw)  # --> 00111100011100010101 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -