0

I need to read the data as UBYTE (8-bit Unsigned Byte) in MATLAB and then used bit shift operators to get two 12-bit streams with 3600000 samples. I have to do that by a command that the first two 12 bit values are contained in the first 3 UBYTEs, 8 bits from the first byte with the first 4 bits from the second byte, then the first 4 bits from byte 2 with all 8 bits from byte 3. Then the process repeats with the next 3 bytes (byte 4-6 etc.) and so on.

First 12 bit value: byte 1 |+ (( byte 2 & 0xf0) << 4)

Second 12 bit value: (( byte 2 & 0xf) << 4) |+ ((byte 3 & 0xf0) >> 4) |+ ((byte 3 & 0xf) << 8)

How can I apply this command in MATLAB?

1 Answers1

0

If I understand correctly then something like this might work:

% Some data for testing
data = randi([0, 256], 1, 9, 'uint8');

% Reshape data so two 12-bit values are in each column
data = reshape(data, 3, []);

m1 = uint16(hex2dec('0f'));
m2 = uint16(hex2dec('f0'));

first_values = uint16(data(1, :)) + bitshift(bitand(uint16(data(2, :)), m2), 4);
second_values = bitshift(bitand(uint16(data(2, :)), m1), 4) ...
  + bitshift(bitand(uint16(data(3, :)), m2), -4) ...
  + bitshift(bitand(uint16(data(3, :)), m1), 8);

I might have made a mistake with the masks, but the bitshift and bitand commands are probably what you are looking for.

The output is two arrays of unit16. If you need the output to be a 12-bit type I'm not sure how best to do that in matlab.

ilent2
  • 5,171
  • 3
  • 21
  • 30
  • Actually, I have to read 3 streams in a binary file and compare the values with a sample file. Stream1: 3600000 Samples, 8-Bits, Start Location: 112 Stream2: 3600000 Samples, 12-Bits, Start Location: 3600112 Stream3: 3600000 Samples, 12-Bits, Start Location: 9000112 I read stream 1 easily by '*uint8'. But about stream2 and 3, I read them by 'ubit12=>uint16' and the values are 0 to 4095. But in the sample file, the values range are between 200 to 1000. When I asked my friend the reason for the difference between my values with the sample file, he advised as above I must apply in MATLAB. – Eliza Telior Dec 16 '20 at 12:43