Read binary file 3 bytes at a time
7 次查看(过去 30 天)
显示 更早的评论
Hi, I am new and I discovered that the fread by default reads a binary file 1 byte at a time, how can I read the file 3 bytes at a time. Thanks
0 个评论
采纳的回答
James Tursa
2015-6-10
编辑:James Tursa
2015-6-10
Try something like this. It reads in the entire file as uint8, groups them in 3 bytes, inserts an extra 0 byte in front of the group of 3, and then reinterprets the bytes as 4 byte unsigned integers. If you don't get the result you want, we may have endian issues to deal with and may need to swap bytes.
x = fread(fid,inf,'*uint8'); % read as uint8
x = reshape(x,3,[]); % groups of 3 in columns
[m,n] = size(x); % get size
x = [zeros(1,n,'uint8'); x]; % insert row of 0's at top to get 4 bytes per number
x = typecast(x(:),'uint32'); % reinterpret bytes as 4-byte unsigned integers
4 个评论
更多回答(2 个)
Guillaume
2015-6-10
A much simpler solution would have been to read the file with a precision of 'ubit24' (or 'bit24' if the integer are signed), which is basically a 3 byte integer:
x = fread(fid, 'ubit24'); %that's it. all done
1 个评论
Walter Roberson
2015-6-10
fread(fid, 3)
4 个评论
James Tursa
2015-6-10
编辑:James Tursa
2015-6-10
Do you mean you have a file of many bytes, and each group of 3 bytes in the file should be read in as an individual number? If so, what type of number? An integer of some sort?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!