Converting hexadecimal to decimal in base 10 using a loop (not function hex2dec)

9 ビュー (過去 30 日間)
Zack Rabas
Zack Rabas 2018 年 11 月 12 日
回答済み: vamsi krishna 2020 年 11 月 8 日
I am running the following code and it is only working when I plug in either just numbers or just letters, but I cannot get it to work for both. For example, "F4E" will not work, but "FF" or "44" work. Why is this happening?
num = input('Enter a hexidecimal number (e.g. FF):', 's');
y = double(num);
x = 0;
for i = 1:length(num)
if y > 47 & y < 58
y = y - 48;
elseif y > 64 & y < 71
y = y - 55;
elseif y > 96 & y < 103
y = y - 87;
end
x = x + y(i) * 16^(length(num)-i);
end

回答 (3 件)

Walter Roberson
Walter Roberson 2018 年 11 月 12 日
if y > 47 & y < 58
should be indexing y(i)

Guillaume
Guillaume 2018 年 11 月 12 日
For reference, here is how I would implement the conversion efficiently in matlab (without using hex2dec):
hex = upper(input('Enter a hexidecimal number (e.g. FF):', 's'));
lookup = [];
lookup(['0':'9', 'A':'F']) = 0:15; %lookup table to convert character to corresponding decimal value
dec = polyval(lookup(hex), 16); %convert characters to decimal value and multiply by corresponding power of 16
No loop needed.

vamsi krishna
vamsi krishna 2020 年 11 月 8 日
a=input("enter the no. in double quotes ");
A=char(a);
l=strlength(a);
i=1;b=0;
while (l>0)
if ((A(i)>='0')&&(A(i)<='9'))
b=(A(i)-48)+b*16;
elseif ((A(i)>='A')&&(A(i)<='E'))
b=(A(i)-55)+b*16;
end
i=i+1;
l=l-1;
end
fprintf("value of given no. %s in decimal is %d",a,b);

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by