Question

I would like to store data in to binary file (precision 'long' - manufacturer's requirement) but after reading file in another software, numbers are rounded. I figured out that when I try to read that file back in MATLAB, numbers are also rounded. Small example:

>> number=-3.913;
>> fid_out=fopen('test','wb');
>> fwrite(fid_out,number,'long');
>> fclose all;
>> fid_in=fopen('test','rb');
>> fread(fid_in,'long')

ans =

    -4

I am sorry, I am not so familiar with binary number type. The reason why I want to use 'long' is external software data decoder. Only information which I got is this:

enter image description here

Some clue?

Was it helpful?

Solution

You got rounded number because you are writing and reading using long, which is a 32 bit integer. To make it work, you need replace long by floating types like double, float etc.

number=-3.913;
fid_out=fopen('test','wb');
fwrite(fid_out,number,'double');
fclose all;
fid_in=fopen('test','rb');
fread(fid_in,'double')

You will get:

ans =

    -3.9130

Edit: If you have to use long, you can first multiple the numbers by a big scale number like 1000 to make it a long and at the same time don't lose the accuracy. Then when loading the data back, you can get the original values by further dividing them by the same scale.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top