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

조회 수: 5 (최근 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 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