2013-02-19 137 views
1

我寫了函數將十萬個十六進制字符串轉換爲值,但需要10秒鐘才能在整個數組上執行。 Matlab有一個函數來做到這一點,所以它更快,也就是說:數組少於1秒?matlab:將十六進制值的字符串轉換爲十進制值?


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

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(:); 
相關問題