pythonmatlabbinary-datauint8array24-bit

MATLAB fread 24 bit convert to Python


I am trying to convert some MATLAB code to Python.

The code reads audio data from serial:

out = fread(s,s.bytesavailable,'uint8'); % [255 205 217 255 212 60 255 207 132 255 ...]

'out' is then saved to a binary file and read back using fread:

fwrite(fid1, out, 'uint8');
[d ~]= fread(fid2,[1 inf],'bit24', 'b');

As expected, with three bytes per sample, 'd' is a third of the length of 'out'. But, I can't work out the way fread reads the binary data.

I have 'out' as a byte array or can open as a binary file in Python and would like to do the conversion from 'out' to 'd' in Python. I have tried methods using numpy, struct, wave, wavio, soundfile but not had much success as I am new to programming. Ideally, I don't want to write to a temporary file and read from it, but this is not essential.

Here is an example of 3 samples if this helps:

out = [255 205 217 255 212 60 255 207 132]
d = [-12839 -11204 -12412] 

Can anyone point me in the right direction?

Thanks


Solution

  • So i just tried something and got the same results as you. I am not sure that it is 100% correct but it should point you in the right direction as you said.

    import struct
    
    def divide_chunks(data: bytearray, n: int):
        for i in range(0, len(data), n):
            yield data[i: i + n]
    
    
    out = bytearray([255, 205, 217, 255, 212, 60, 255, 207, 132])
    
    list_24bit = list(divide_chunks(out, 3))
    list_32bit = list(map(lambda x: bytearray([0 if x[0] < 128 else 255, *x]), list_24bit))
    
    d = list(map(lambda x: struct.unpack('>i', x), list_32bit))