Importing and exporting data: binary files

A binary file contains data in its most compact form. Numbers in a binary file are stored in a continuous stream, with no spaces separating them. This type of file is not intended to be read by person, but by a computer.

In order to tell the numbers apart, the computer program reading the data must know exactly the format in which the data was written.

MATLAB can read and write binary files using the fopen, fread/fwrite, and fclose commands.

To read a binary file into MATLAB, we need to open the file for reading and scan the data thereafter into a new variable using the correct format.

fid = fopen('example.bin','r'); % Open the binary file for reading with file pointer fid
[data,count] = fread(fid, 'int16'); % Scan the data into a vector, in this case called data
fclose(fid); % Close the file

There are a large number of binary data formats that MATLAB can read and write. These include:

'uchar' unsigned character, 8 bits
'schar' signed character, 8 bits
'int8' integer, 8 bits
'int16' integer, 16 bits
'int32' integer, 32 bits
'uint8' unsigned integer, 8 bits
'uint16' unsigned integer, 16 bits
'single' floating point, 32 bits
'double' floating point, 64 bits

Picking the right data format with which to read a particular binary file requires either knowledge of how the file was written or plain old trial and error!

The file length can provide one useful clue. If you know a file contains 1024 data points and the length of the file is 2048 bytes, you know that the data is saved using 16 bits per data point.

For more information on data formats, including accounting for the order in which bytes are written on different types of computers ("big-endian" vs. "little-endian"), see MATLAB's help pages on fopen and fread.