MATLAB Answers

writing a 16-bit binary file

56 views (last 30 days)
Robert
Robert on 12 Jan 2014
Commented: Walter Roberson on 8 Jul 2021
Hi there,
I am trying to produce a text file of 16-bit binary to test a C program.
I can write to a file, but it writes to the file in scientific notation. I am basically after a file with about 2048 lines of 16-bit ones and zeros or alternatively, just in standard form as in: 32767 -32768 not 3.2767e -4
if that could be put in the form of
0000 0010 1100 1000
kind of data that would be even better. I can only get this far. I am using a sine wave to generate the numbers, and the data only need be approximate, as it is to test a C routine that takes data straight from a circuit.
x = 0:1:1024; y = 32767*sin(x); fid = fopen('data.txt','w'); writebytes(fid, '%5.0d\n',y); fclose(fid);
kind regards Rob
  2 Comments
Walter Roberson
Walter Roberson on 23 Nov 2019
if isa(TheNumber, 'uint8')
output = uint16(TheNumber);
elseif isa(TheNumber, 'int8')
output = typecast( int16(TheNumber), 'uint16');
else
output = typecast(TheNumber, 'uint16');
end
If the original number was more than 16 bits wide then output will be a vector of uint16 . It is not obvious what 16 bit number you would want output if the input was, for example, a double.

Sign in to comment.

Answers (3)


Jan
Jan on 12 Jan 2014
writebytes is thought for mupad objects. fprintf will be better:
fid = fopen('data.txt','w');
fprintf(fid, '%5.0d\n', y);
fclose(fid);

Robert
Robert on 12 Jan 2014
No, this is still giving me the text in the form: 3e+04
I need the data written in the file as either 16 bit binary, or just plain decimal if that is all matlab can do.
  5 Comments
Walter Roberson
Walter Roberson on 8 Jul 2021
By the way, these days dec2bin handles negative values.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!