I have tried reading a binary file 64 bits at a time, and is not behaving as expecting.
I have a binary file with the word = 0xFAFAFAFA00010001, if I read it like this:
word = fread(fid,1,'uint64'), and look at hex2dec(word), the word is 0xFAFAFAFA00010000 (yes, one bit has been changed).
but if I read:
word_l = fread(fid,1,'uint64'); word_h = fread(fid,1,'uint64'), I get 0x00010001 as hex2dec(word_l) and 0xFAFAFAFA as hex2dec(word_h).
I do not know if the problem is on the read (don't think so), or the 64bit management (I think is here), but I tried doing this too:
a=hex2dec('FAFAFAFA');
b = hex2dec('00010001');
dec2hex(bitshift(a,32))
% Output is 0xFAFAFAFA00000000
dec2hex(b)
% Output is 0x00010001
dec2hex(bitor(bitshift(a,32),b))
% Output is 0xFAFAFAFA00010000
Is there an issue with matlab and numbers larger than 53 bits? 60 bits?

 Accepted Answer

Try reading and keeping the type as uint64 (using the *) instead of converting to double:
word = fread(fid,1,'*uint64');

3 Comments

It does not fix it, this code generates my issue:
% Write
fid = fopen('test.bin','wb');
fwrite(fid, hex2dec('00010001'), 'uint32' )
fwrite(fid, hex2dec('FAFAFAFA'), 'uint32' )
fclose(fid);
% Read by 32 bits at a time
fid = fopen('test.bin','rb');
dec2hex(fread(fid,1,'uint32'))
dec2hex(fread(fid,1,'uint32'))
fclose(fid);
% Read one 64 bit word
fid = fopen('test.bin','rb');
word = fread(fid,1,'*uint64')
uint64(hex2dec('FAFAFAFA00010001'))
dec2hex(word)
fclose(fid);
The second case works, the word does not match the value
James Tursa
James Tursa on 29 Sep 2020
Edited: James Tursa on 29 Sep 2020
I'm not sure what the issue is now. If you use the '*uint64' input format, the 64-bits are read into a uint64 type and all bits are retained. If you use the 'uint64' input format (without the asterisk) the bits are read and then converted to a double, which will lose trailing bits because of the mantissa limitation. Why isn't the '*uint64' format doing what you want?
The hex2dec('FAFAFAFA00010001') function also converts the value to double, losing trailing bits. So that is not a good comparison.
You are right, I had to go to another hex to decimal convertion and then compare to the word read with '*uint64'.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!