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

2 Ansichten (letzte 30 Tage)
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

Antworten (3)

Walter Roberson
Walter Roberson am 12 Nov. 2018
if y > 47 & y < 58
should be indexing y(i)

Guillaume
Guillaume am 12 Nov. 2018
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 am 8 Nov. 2020
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);

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by