フィルターのクリア

How to read 8-byte floating point numbers from binary?use fread

28 ビュー (過去 30 日間)
aijiangzhao aixuwu
aijiangzhao aixuwu 2021 年 10 月 28 日
編集済み: Jan 2021 年 11 月 12 日
fseek(fid,56,'bof');
x = fread(fid,1,'float64','b')
  3 件のコメント
aijiangzhao aixuwu
aijiangzhao aixuwu 2021 年 10 月 29 日
This is correct, but a new question has arisen. For example, how can "DC 88 12 C0 C1 4F 7C A9" be replaced with "C0 12 88 DC A9 7C 4F C1"? Then read as double-precision floating point
Walter Roberson
Walter Roberson 2021 年 10 月 29 日
When you fopen you should specify the byte order as the third parameter to fopen, unless you are reading from something with mixed orders.
If you are reading from something with mixed orders but know the order for one particular binary fread then specify the byte order as a parameter to fread.
If you are reading a sequence of bytes at one time and regrouping them (such as if you were reading a structure with mixed datatype) then if necessary use swapbytes after any necessary typecast()

サインインしてコメントする。

採用された回答

Jan
Jan 2021 年 10 月 30 日
編集済み: Jan 2021 年 11 月 12 日
With 'ieee-le' format the bytes are read in the order [8,7,6,5,4,3,2,1], with 'ieee-be' as [1,2,3,4,5,6,7,8]. There is no format to store doubles with the byte order [4,3,2,1,8,7,6,5]. Yo you have to convert the order manually by reading the bytes, mix them as wanted and use typecast for the conversion.
[EDITED] As code:
bytes = fread(fid, 8, '*uint8');
bytes = bytes([4,3,2,1,8,7,6,5]);
value = typecast(bytes, 'double')
  8 件のコメント
Jan
Jan 2021 年 11 月 12 日
As I have suggested already, except for the changed byte order:
% fseek(fid, 56, 'bof');
% bytes = fread(fid, 8, '*uint8');
% Manually:
bytes = uint8(sscanf('C5 B9 FB 60 C1 4B FD CA', '%x')).';
value = typecast(fliplr(bytes), 'double') % As your fread('float64')
value = -8.0410e+27
% [197, 185, 251, 96, 193, 75, 253, 202]
bytes = bytes([4,3,2,1,8,7,6,5]);
value = typecast(bytes, 'double')
value = -3.6689e+06
Now the byte order and the order of 4-Byte-blocks is swapped.
aijiangzhao aixuwu
aijiangzhao aixuwu 2021 年 11 月 12 日
Thank you very much for solving the problem that caused me a lot of headaches.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLanguage Support についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by