# How to convert data byte by byte

21 views (last 30 days)
Tayyaba Abro on 27 Jan 2021
Answered: Jan on 27 Jan 2021
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 ?
Jan on 27 Jan 2021
Typing an answer would be easier, if the file or its contents is provided as text.
James Tursa on 27 Jan 2021

Jan on 27 Jan 2021
Edited: Jan on 27 Jan 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:
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
fclose(fid);
Maybe you want to import the numbers and convert them from hex to decimal?
values = sscanf(S, '|%x', [1, inf]);
To clarify this, please post an example with input data and the wanted output.
Tayyaba Abro on 27 Jan 2021
Edited: Tayyaba Abro on 27 Jan 2021
Actually I am taking data from wireshark in text format so it is showing like the picture that I have shared above. When taking data in pcap format it shows ASCII data but im unable to extract that
Jan on 27 Jan 2021
Edited: Jan on 27 Jan 2021
Another option:
fid = fopen('packettext.txt', 'r');
if fid < 0, error('Cannot open file.'); end
bytes = fscanf(fid, '|%x', [1, inf]);
fclose(fid);

David Hill on 27 Jan 2021
d=hex2dec(regexp(a,'[0-9a-f]+','match'));

Steven Lord on 27 Jan 2021
s = '|0|01|00|5e|'
s = '|0|01|00|5e|'
data = split(s, '|')
data = 6x1 cell array
{0×0 char} {'0' } {'01' } {'00' } {'5e' } {0×0 char}
d = hex2dec(data)
d = 6×1
0 0 1 0 94 0
If you want to eliminate the first and last 0 in d, trim the leading and trailing | characters from s before splitting.

Jan on 27 Jan 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.