Why MATLAB swaps the nibbles while reading a byte as two nibbles. ?

I have a binary file with 12 bit data. If I read the data nibble wise in C++, say as ABC DEF GHI JKL then I get wrong values. If I use MATLAB function to read as nibble stream then I get correct output, though on exploring I found Matlab reads the data as BAD CFE HGJ ILK. Here each alphabet is a nibble. Three nibbles thus make one data point for me in 12 bit. Is it possible that FPGA writing the binary data also writes it as swapped nibbles so that when MATLAB reads it as swapped nibbles the data gets read correctly ?
Code: As @Guillaume pointed out, I am posting some code used. Please see the MATLAB as well as C code for reference.
FILE *ptr_myfile;
ptr_myfile=fopen(ImagePath,"rb");
FILE *ptr_write;
ptr_write=fopen("FileOut.pgm","w");
fseek( ptr_myfile, 177, SEEK_SET );
if (!ptr_myfile)
{
printf("Unable to open file!");
fclose(ptr_myfile);
}
char bytestream[3];
uint16_t nibble[6] = {};
while(1)
{
if( feof(ptr_myfile) )
{
fclose(ptr_myfile);
break;
}
fread(&bytestream,1,3,ptr_myfile); // Assumption : The binary file has the data in following format BAD CFE while ABC and DEF are actual pixel values, each character is a nibble
nibble[0] = (bytestream[0] & 0xF0) >> 4; // Reads B
nibble[1] = bytestream[0] & 0x0F; // Reads A
nibble[2] = (bytestream[1] & 0xF0) >> 4; // Reads D
nibble[3] = bytestream[1] & 0x0F; // Reads C
nibble[4] = (bytestream[2] & 0xF0) >> 4; // Reads F
nibble[5] = bytestream[2] & 0x0F; // Reads E
fprintf(ptr_write,"%d",(nibble[3] + 16*nibble[0] + 256*nibble[1]));
fputc(' ',ptr_write);
fprintf(ptr_write,"%d",( nibble[4] + 16*nibble[5] + 256*nibble[2]));
fputc(' ',ptr_write);
}
Matlab Code:
fseek(fileID, 174, 'bof');
stream4 = fread(fileID, 'ubit4=>uint16');
stream4_1 = stream4(1:3:end-2);
stream4_2 = stream4(2:3:end-1);
stream4_3 = stream4(3:3:end);
stream12 = stream4_1 .* 256 + stream4_2 .* 16 + stream4_3;

2 Comments

"Is it possible that ..."
Maybe, maybe not... Without seeing how you've implemented the reading/writing, it's impossible to say.
Show us some code.
@Guillaume: Please check the updated question with code.

Sign in to comment.

Answers (1)

If you're opening the file for reading using fopen specify the machinefmt input argument to use the correct endianness. Alternately the swapbytes function may be of use to you.

1 Comment

Is there anything like nibble endian-ness as well. I am under the impression that it is only for bytes. Can you confirm that MATLAB internally swaps the nibbles while using:
stream4 = fread(fileID, 'ubit4=>uint16');

Sign in to comment.

Categories

Find more on Signal Processing Toolbox in Help Center and File Exchange

Products

Asked:

on 17 Aug 2017

Edited:

on 18 Aug 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!