How does fread bring in a signed integer?

11 次查看(过去 30 天)
Hello,
I am working with the reading in of binary files and I had a question on the fread function.
Basically, the datagram format specifies that the data samples are stored as signed 16bit integer (2's compliment). From looking around, there are a number of methods for handling signed numbers (2's compliment, 1's compliment, signed magnitude, offset...). So when i use fread() as follows:
s = fread(fid,256,'int16',0,'b');
Are the numbers read in as 2's compliment binary, or signed magnitude, or something else? I have to image it matters but I can't find what method MATLAB uses.
Thanks for any and all help!
  1 个评论
Rik
Rik 2019-2-19
I couldn't find it in the doc either. IIRC almost everyone uses 2's complement, so I would assume Matlab does as well. You can read bit by bit if you want to make sure either way. There are only 2^16-1 numbers you need to check, which shouldn't take more than a few minutes to check.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2019-2-20
fread() always does binary reads. Representation is internal representation.
All modern computer general purpose systems use 2's complement for signed integers.
IEEE 754 Binary Single and Binary Double have very specific formats, both of which happen to be Signed Magnitude.
The internal representation for some DSP might be different. The representation for (V)HDL and FPGA often uses Fixed Point instead of Floating Point, and in the cases that do support floating point, often it is only single precision and typically it is not completely IEEE 754 compliant (because treatment of NaN turns out to be pretty expensive, especially Signaling NaN.)
There is a lingering question, which is what byte order is used for fread. The answer to that is that if you fopen() and fread() without specifying the byte order, then the default is to use the same byte order as the host system, which is "little endian" for all x86 and x64 architectures. When dealing with files that are not "scratch" files, temporary files for use within one program, then it is always better form to specify the byte order parameter at the time of fopen(): people reading your code should not have to guess or do a bunch of research in compiler manuals to find out which endian your files are going to be.
Reminder: the standard for TCP and UDP is "Network Byte Order", which is "big endian", so you should convert binary data to network byte order before sending it -- or if you are developing your own protocol then you can define (and document!!!) little-endian order to make it easier for Windows programmers.

更多回答(0 个)

标签

Community Treasure Hunt

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

Start Hunting!

Translated by