[Numpy-discussion] Add count (and dtype) to packbits

Neal Becker ndbecker2 at gmail.com
Wed Jul 21 08:39:56 EDT 2021


In my application I need to pack bits of a specified group size into
integral values.
Currently np.packbits only packs into full bytes.
For example, I might have a string of bits encoded as a np.uint8
vector with each uint8 item specifying a single bit 1/0.  I want to
encode them 4 bits at a time into a np.uint32 vector.

python code to implement this:

---------------
def pack_bits (inp, bits_per_word, dir=1, dtype=np.int32):
    assert bits_per_word <= np.dtype(dtype).itemsize * 8
    assert len(inp) % bits_per_word == 0
    out = np.empty (len (inp)//bits_per_word, dtype=dtype)
    i = 0
    o = 0
    while i < len(inp):
        ret = 0
        for b in range (bits_per_word):
            if dir > 0:
                ret |= inp[i] << b
            else:
                ret |= inp[i] << (bits_per_word - b - 1)
            i += 1
        out[o] = ret
        o += 1
    return out
---------------

It looks like unpackbits has a "count" parameter but packbits does not.
Also would be good to be able to specify an output dtype.


More information about the NumPy-Discussion mailing list