How to load 4 bit data into a numpy array

I have a binary data file containing 8 bit complex samples - i.e. 4 bits and 4 bits for imaginary and real (Q and I) components from MSB to LSB.

How can I get this data into a numpy array of massive numbers?

+3


source to share


2 answers


There is no support for doing 8-bit complex numbers (4-bit real, 4-bit imaginary). So the following method is a good way to efficiently read them into separate numpy arrays for complex and imaginary ones.

values = np.fromfile("filepath", dtype=int8)
real = np.bitwise_and(values, 0x0f)
imag = np.bitwise_and(values >> 4, 0x0f)

      

then if you want one complex array,

signal = real + 1j * imag

      



There are many ways to convert two real arrays to a complex array: fooobar.com/questions/141756 / ...


If the values ​​are 4-bit ints that can be negative (i.e., two's complement applies), you can use bit shift arithmetic to properly allocate the two channels:

real = (np.bitwise_and(values, 0x0f) << 4).astype(np.int8) >> 4
imag = np.bitwise_and(values, 0xf0).astype(int) >> 4

      

+3


source


Using this answer to read data one byte at a time, this should work:



with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)
        real = byte >> 4
        imag = byte & 0xF
        # Store numbers however you like

      

+3


source







All Articles