How to convert data byte by byte
17 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have read a file and data im getting is shown below. I have to convert this data byte by byte in decimal number please tell me how can I do that ?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/501848/image.png)
2 Commenti
Jan
il 27 Gen 2021
Typing an answer would be easier, if the file or its contents is provided as text.
Risposta accettata
Jan
il 27 Gen 2021
Modificato: Jan
il 27 Gen 2021
Do you really mean byte by byte? The variable read conatins 16 bit characters of the text as unicode, so a byte by byte conversion is:
read = '|0|01|00|5e|'
typecast(uint16(read), 'uint8')
The original text might be a ASCII text, then import it as bytes directly:
fid = fopen('packettext.txt', 'r');
if fid < 0, error('Cannot open file.'); end
bytes = fread(fid, inf, '*uint8');
fclose(fid);
Maybe you want to import the numbers and convert them from hex to decimal?
S = fileread('packettext.txt');
values = sscanf(S, '|%x', [1, inf]);
To clarify this, please post an example with input data and the wanted output.
Più risposte (3)
Steven Lord
il 27 Gen 2021
s = '|0|01|00|5e|'
data = split(s, '|')
d = hex2dec(data)
If you want to eliminate the first and last 0 in d, trim the leading and trailing | characters from s before splitting.
0 Commenti
Jan
il 27 Gen 2021
A comparison of the runtimes:
s = repmat('|0|01|00|5e', 1, 2000);
tic
for k = 1:100
d = hex2dec(regexp(s, '[0-9a-f]+', 'match'));
end
toc
tic
for k = 1:100
d = hex2dec(split(s, '|'));
end
toc
tic
for k = 1:100
d = sscanf(s, '|%x');
end
toc
tic
for k = 1:100
d = sscanf(strrep(s, '|', ' '), '%x');
end
toc
% Elapsed time is 0.909770 seconds.
% Elapsed time is 0.424414 seconds.
% Elapsed time is 0.272269 seconds.
% Elapsed time is 0.163054 seconds.
0 Commenti
Vedere anche
Categorie
Scopri di più su Low-Level File I/O in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!