Search code examples
matlabwavbinary-databit

MATLAB reading bit by bit from a binary file


I am able to successfully read in a .wav file with the following code.

[y,Fs,nbits,opts] = wavread('MyFile.wav','native')

So I now know from the file the data which is stored in y, the sample rate (Fs), nbits which is 16 and 'native' informs me the data is of uint16 type.

Now I want to read a data value bit by bit. Each data value I already know is made up of 16 bits.

Is there a way for one data value to be read bit by bit. So for a uint16 data value I would like to read bit 0 and bits 1-15. I would then hope reading bit 0 gives me a value and bits 1-15 gives me a value. Is this possible?

I know of fread but I only know how to use this when reading byte by byte.


Solution

  • Well it is always nice when you manage to answer your own question. So here is what I found I could do:

    [y,Fs,nbits,opts] = wavread('MyFile.wav','native')
    
    Sample = y(1:10,1); %Takes 10 data values
                        %I know I have uint16 data type
    
    %I then take a bit at a time from the data value
    
    Bit_16 = bitget(Sample(:,1),16);
    Bit_15 = bitget(Sample(:,1),15);
    Bit_14 = bitget(Sample(:,1),14);
    and so on . . . 
    
    %I could then produce a matrix from the individual bit values
    
    Matr = [Bit_16,Bit_15,Bit_14,...,];
    
    %Each row of the matrix is now the desired binary number
    %Next steps, convert to string and then to a decimal number
    
    Str = num2str(Matr);
    15-bit value = bin2dec(Str); 
    

    You can then do the same above for just 1-bit