How to save as uint16 in file without using all the bytes?

7 views (last 30 days)
This is a simple example of what I want to do:
num = 4
fid = fopen('test.yuv','w+');
fwrite(fid,num,'uint16');
fclose(fid);
I need to save 4 in test.yuv but it keeps saving an array of
4 0
because of uint16. Is there a way to save only 4 in the file?
  • It has to be in .yuv with uint16.
  1 Comment
Guillaume
Guillaume on 2 Aug 2018
Edited: Guillaume on 2 Aug 2018
Well, you either want to save 4 as uint16, in which case, it'll take two bytes, or you want to save it as one byte in which case it can't be uint16 but has to be uint8.
You can't have it both ways.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 2 Aug 2018
Edited: Walter Roberson on 2 Aug 2018
It does not save an array with two positions in the file. It saves a single value which happens to require two bytes to represent.
The 4 0 that you see in the file are uint8(4) uint8(0), which is the way that uint16(4) is stored in memory with the way you are writing the file.
When you fopen() the file you let the byte order default to "n" (native), which is to say "whatever is right for the machine the code is running on." For a number of releases now, MATLAB has only been supported on systems based on the x86 or x64 architectures, both of which use "little endian", which means that in the actual memory order of the two-byte value uint16(4), the least significant byte appears first in memory, so inside your computer uint16(4) is stored in the order 4 0, binary 00000100 00000000 and not in the order 00000000 00000100 . By default, the 00000100 00000000 order is the one written to files. To change that, you would need to pass a third parameter to fopen(), such as fopen('test.yuv', 'w+', 'ieee-be'). That would not affect the number of bytes written into the file: it would just affect the order, so that it became binary 00000000 00000100, decimal 0 4

Community Treasure Hunt

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

Start Hunting!