将十六进制字符串(以冒号分隔)转换为十进制数组:Matlab/Octave
Converting hex string (delimited with colons) to decimal array: Matlab/Octave
我正在从文件中提取一些数据,包括如下字符串:
n ={[1,1] = 0:7:80:bc:eb:64
[2,1] = 0:7:80:bc:eb:69
[3,1] = 0:7:80:bc:eb:69
[4,1] = 0:7:80:bc:eb:69
}
我需要将“0”更改为“00”,将“7”更改为“07”。然后用函数hex2dec
把它转换成十进制数。
我正在使用以下代码:
r=strrep(0:7:80:bc:eb:69 , ':', '');
m= hex2dec(r)
也许有更好的方法?
您可以使用 strsplit
在 :
上拆分 每个字符串 。这给出了一个字符串元胞数组(字符向量),您可以直接将其传递给 hex2dec
;不需要零填充:
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
k = 1; % select one cell
t = strsplit(n{k}, ':');
result = hex2dec(t);
这给出了
t =
'0' '7' '80' 'bc' 'eb' '64'
result =
0
7
128
188
235
100
要从 所有字符串 中获取数字作为矩阵,请使用 strjoin
, apply the above, and then apply reshape
:
连接元胞数组的字符串
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
nj = strjoin(n, ':');
t = strsplit(nj, ':');
result = hex2dec(t);
result = reshape(result, [], numel(n)).';
这给出了
result =
0 7 128 188 235 100
0 7 128 188 235 105
0 7 128 188 235 105
0 7 128 188 235 105
strsplit 和 hex2dec 工作正常,正如上面的答案所建议的那样。我正在通过 sscanf 提供更简单、更快速的解决方案:
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
t = sscanf(n{1}, '%x:')'
t =
0 7 128 188 235 100
我正在从文件中提取一些数据,包括如下字符串:
n ={[1,1] = 0:7:80:bc:eb:64
[2,1] = 0:7:80:bc:eb:69
[3,1] = 0:7:80:bc:eb:69
[4,1] = 0:7:80:bc:eb:69
}
我需要将“0”更改为“00”,将“7”更改为“07”。然后用函数hex2dec
把它转换成十进制数。
我正在使用以下代码:
r=strrep(0:7:80:bc:eb:69 , ':', '');
m= hex2dec(r)
也许有更好的方法?
您可以使用 strsplit
在 :
上拆分 每个字符串 。这给出了一个字符串元胞数组(字符向量),您可以直接将其传递给 hex2dec
;不需要零填充:
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
k = 1; % select one cell
t = strsplit(n{k}, ':');
result = hex2dec(t);
这给出了
t =
'0' '7' '80' 'bc' 'eb' '64'
result =
0
7
128
188
235
100
要从 所有字符串 中获取数字作为矩阵,请使用 strjoin
, apply the above, and then apply reshape
:
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
nj = strjoin(n, ':');
t = strsplit(nj, ':');
result = hex2dec(t);
result = reshape(result, [], numel(n)).';
这给出了
result =
0 7 128 188 235 100
0 7 128 188 235 105
0 7 128 188 235 105
0 7 128 188 235 105
strsplit 和 hex2dec 工作正常,正如上面的答案所建议的那样。我正在通过 sscanf 提供更简单、更快速的解决方案:
n = {'0:7:80:bc:eb:64';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69';
'0:7:80:bc:eb:69'}; % data: cell array of strings
t = sscanf(n{1}, '%x:')'
t =
0 7 128 188 235 100