Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using the <a href="https://pypi.python.org/pypi/bitarray" rel="nofollow">bitarray module</a>, you can do it a lot quicker for big numbers:</p> <p>Benchmarks (factor 2.4x speedup!):</p> <pre><code>janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(10000)" 10 loops, best of 3: 251 msec per loop janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(100)" 1000 loops, best of 3: 700 usec per loop janus@Zeus /tmp % python3 -m timeit -s "import sevenbittoint, os" "sevenbittoint.sevenbittoint(os.urandom(10000))" 10 loops, best of 3: 73.7 msec per loop janus@Zeus /tmp % python3 -m timeit -s "import quick, os" "quick.quick(os.urandom(10000))" 10 loops, best of 3: 179 msec per loop </code></pre> <p>quick.py (from Mark Byers):</p> <pre><code>def quick(bites): i = 0 for b in bites: i &lt;&lt;= 7 i += (b &amp; 0x7f) #i += b return i </code></pre> <p>sevenbittoint.py:</p> <pre><code>import bitarray import functools def inttobitarray(x): a = bitarray.bitarray() a.frombytes(x.to_bytes(1,'big')) return a def concatter(accumulator,thisitem): thisitem.pop(0) for i in thisitem.tolist(): accumulator.append(i) return accumulator def sevenbittoint(bajts): concatted = functools.reduce(concatter, map(inttobitarray, bajts), bitarray.bitarray()) missingbits = 8 - len(concatted) % 8 for i in range(missingbits): concatted.insert(0,0) # zeropad return int.from_bytes(concatted.tobytes(), byteorder='big') def tst(): num = 32768 print(bin(num)) print(sevenbittoint(num.to_bytes(2,'big'))) if __name__ == "__main__": tst() </code></pre> <p>tst.py:</p> <pre><code>import os import quick import sevenbittoint def tst(sz): bajts = os.urandom(sz) #for i in range(pow(2,16)): # if i % pow(2,12) == 0: print(i) # bajts = i.to_bytes(2, 'big') a = quick.quick(bajts) b = sevenbittoint.sevenbittoint(bajts) if a != b: raise Exception((i, bin(int.from_bytes(bajts,'big')), a, b)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload