I have a list/array of numbers, which I want to save to a binary file. The crucial part is, that each number should not be saved as a pre-defined data type. The bits per value are constant for all values in the list but do not correspond to the typical data types (e.g. byte or int).
import numpy as np
# create 10 random numbers in range 0-63
values = np.int32(np.round(np.random.random(10)*63));
# each value requires exactly 6 bits
# how to save this to a file?
# just for debug/information: bit string representation
bitstring = "".join(map(lambda x: str(bin(x)[2:]).zfill(6), values));
print(bitstring)
In the real project, there are more than a million values I want to store with a given bit dephts. I already tried the module bitstring, but appending each value to the BitArray costs a lot of time...
PackedIntArrayclass in this answer of mine might be useful (although it's implemented usingBitArray). Regardless, there's a fair amount processing involved in doing what you want—especially for a long list of numbers—and there's no getting around it.BitArrayis written in C, so should be close to as fast as you're going to get without writing your own custom C extension.