Reading binary file with fread and typecast

I am trying to read a binary file with columns of data in various format (int32,uint32,int16,int64,etc.). As there are many columns of data, I want to speed up my reader by reading the whole file at once in increments of 8 bits and then recovering the various formats using the typecast function.
% Move to start of binary file (header is ascii format of 3759 bytes)
fseek(fid,3759,'bof');
% Read the data file as 8 bit increments (each row has 16660 bytes)
data = uint8(fread(fid,[16660,Inf],'16660*uint8'));
% Attempt to recover first data element of type int32
val1 = data(1:4,1);
val2 = typecast(uint8(val1),'int32');
Running this code I get that
val1 = [0 0 22 229]
val2 = -451543040
Whereas the true value should be 5861. What am I doing wrong?

 採用された回答

James Tursa
James Tursa 2017 年 7 月 11 日

0 投票

try
val2 = swapbytes(typecast(uint8(val1),'int32'));

1 件のコメント

Tim Jensen
Tim Jensen 2017 年 7 月 11 日
Thanks, this solved the issue.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCell Arrays についてさらに検索

質問済み:

2017 年 7 月 11 日

コメント済み:

2017 年 7 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by