Effacer les filtres
Effacer les filtres

How can I combine binary data in memory, and use fwrite for only one time to write all the data?

9 vues (au cours des 30 derniers jours)
I need to write some large data in multiple loops. Each time, the data being written by fwrite is very small, and the frequent usage of fwrite seems to slow down my code. Here's an example:
% For loop starts:
fwrite(fid,dataA,'uint32');
fwrite(fid,dataB,'uint16');
fwrite(fid,dataC,'char');
...
% For loop ends
Is it possible if I combine dataA, dataB, and dataC together, so I can use fwrite for only one time, which will very likely be quicker.
  2 commentaires
per isakson
per isakson le 7 Août 2021
Modifié(e) : per isakson le 7 Août 2021
The documentation on fwrite() says:
precision Class and size of values to write
'uint8' (default) | character vector | string scalar
which answers your question: No
per isakson
per isakson le 8 Août 2021
The documentation on fopen() says:
permission — File access type
[...]
'A' Open file for appending without automatic flushing of the current output buffer.
'W' Open file for writing without automatic flushing of the current output buffer.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 7 Août 2021
You have a problem: you are using a binary file, but you are not using a constant number of bytes each time, and you are not putting in any kind of count or marker to know how large the variable-length data is.
You are not using a constant number of bytes each time because you are requesting 'char', and "The MATLAB®char type is not a fixed size, and the number of bytes depends on the encoding scheme associated with the file. Set encoding with fopen."
For example if your dataC includes '∑' then that is char(8721) which requires at least two bytes to write out.
We do not know what encoding you are using, so we have to ask fopen() what is being used, and then we have to ask unicode2native to translate the characters into a byte stream according to the encoding.
[~, ~, ~, encoding] = fopen(fid);
byte_A = typecast(dataA, 'uint8');
byte_B = typecast(dataB, 'uint8');
byte_C = unicode2native(dataC, encoding);
bytes = [byte_a, byte_B, byte_C];
fwrite(fid, bytes, 'uint8');
  2 commentaires
Jianfei
Jianfei le 7 Août 2021
Thank you for you answer. Is there any method to translate uint32 and uint16 to uint8?
Walter Roberson
Walter Roberson le 7 Août 2021
That's what the typecast() does.
dataA = randi([0 65535], 'uint16')
dataA = uint16 44301
typecast(dataA, 'uint8')
ans = 1×2
13 173
double(ans(2))*256+double(ans(1)) %cross-check
ans = 44301

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by