Help for setting the formatSpec when reading hexadecimal

Hello, this is Matthew.
I'm trying to read a file that contains hexadecimal. This is the pattern. Or check the attached file, please.
00b7 17ff 5b3f 1700 c84b 1eff b398 1d00
a577 00ff 15b3 00ff 00b7 17ff 5b3f 1700
c84b 1eff b398 1d00 a577 00ff 15b3 00ff
00b7 17ff 5b3f 1700 6929 1eff b398 1dff
a577 00ff b690 00ff 00b7 1700 5b3f 1700
6929 1eff b398 1dff a577 00ff b690 00ff
So I wrote that
formatSpec = '%04x %04x %04x %04x %04x %04x %04x %04x\n';
fid = fopen(filename, 'r');
hex = fscanf(fid, formatSpec);
sizeHex = length(hex); % the length shows 0
How should I change the format spec to read the hexadecimal correctly?
-Regards, Matthew

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 19 Mär. 2018
That file does not contain hexadecimal. It is a binary file. You can use
data = fread(fid, '*uint16', [1 inf]);
If you want to see the hex equivalent you can
disp(dec2hex(data))
Watch out for byte order questions. The above code will treat the byte stream as being the in-memory byte order, which is "little endian" -- the first byte of the file would be the low byte (least significant) of the uint16. You can add 'ieee-be' to the fopen() to have it treat the first byte of the file as the high byte (most significant) of the uint16.

3 Kommentare

Thanks for your kind reply, Walter. May I ask one additional question?
As you saw my attached file, the first line goes like this;
abf3 1700 8463 17ff 7de4 1e00 23d5 1cff
Your code
data = fread(fid, '*uint16', [1 inf]);
reads the first input (abf3 in little endian, 62379) correctly.
I expected to read 1700, 8463, 17ff, ... in little endian. However,
Matlab read 33792 (skipped 17 and read 8400),
65303 (skipped 63 and read 17FF), and so on.
Is this due to the space/tab in the file?
What option should I add for the fread function?
-Regards, Matthew
Sorry, should be
data = fread(fid, [1 inf], '*uint16');
You don't have to apologize! :D
You saved my life. Thanks~
-Regards, Matthew

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by