matlab:将十六进制值的字符串转换为十进制值?

时间:2013-02-19 16:25:32

标签: matlab

我编写了将100,000个十六进制字符串转换为值的函数,但是在整个数组上执行需要10秒。 Matlab是否具有执行此操作的功能,因此它更快,...即:阵列不到1秒?


function x = hexstring2dec(s)
[m n] = size(s);

x = zeros(1, m);
for i = 1 : m
    for j = n : -1 : 1
       x(i) = x(i) + hexchar2dec(s(i, j)) * 16 ^ (n - j);
    end
end

function x =  hexchar2dec(c)

if c >= 48 && c <= 57
    x = c - 48;
elseif c >= 65 && c <= 70
    x = c - 55;
elseif c >= 97 && c <= 102
    x = c - 87;
end

2 个答案:

答案 0 :(得分:5)

尝试使用hex2dec。它应该比循环每个字符更快更快。

答案 1 :(得分:2)

shoelzer's答案显然是最好的 但是,如果您想自己进行转换,那么您可能会觉得这很有用:

假设s是一个char矩阵:所有十六进制数的长度相同(必要时填零),每行都有一个数字。然后

ds = double( upper(s) ); % convert to double
sel = ds >= double('A'); % select A-F
ds( sel ) = ds( sel ) - double('A') + 10; % convert to 10 - 15
ds(~sel)  = ds(~sel) - double('0'); % convert 0-9
% do the sum through vector product
v = 16.^( (size(s,2)-1):-1:0 );
x = s * v(:);