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

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Resizing 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