我从文件中提取一些数据,包括如下字符串:
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)
也许还有更好的方法吗?
答案 0 :(得分:3)
您可以使用strsplit
在:
上拆分每个字符串。这给出了一个字符串数组(char矢量),你可以直接传递给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
加入单元格数组的字符串,应用上述内容,然后应用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
答案 1 :(得分:3)
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