Converting base N to base 10
Afficher commentaires plus anciens
The question quest us to write a function BaseNBase10 that has two inputs: 1) a string representation of a number (positive integer) in base N ; 2) the base of the number. The function returns the equivalent number in base 10 (scalar).
However, when I run my test case for base 16, it can not read in letter as a part of the vector. What should I do so this function can run with a string input and a number output.
writeCodeToTestMyCode;
function writeCodeToTestMyCode
% disp(strcat("Expected: 10 and Actual: ", num2str(bbaseNtobase10("1010",2))));
% disp(strcat("Expected: 157 and Actual: ", num2str(bbaseNtobase10("235",8))));
disp(strcat("Expected: 693 and Actual: ", num2str(basse10tobaseN("2B5",16))));
end
function [base10number] = bbaseNtobase10(baseNnumber,baseN)
workingnumber = num2str(flip(baseNnumber));
valueinbase10 = 0;
finalvalue = 0;
if baseN == 16
for j = 1:length(workingnumber)
if strcmp(workingnumber(i), "A") == 1
workingnumber(i) = 10;
elseif strcmp(workingnumber(i), "B") == 1
workingnumber(i) = 11;
elseif workingnumber(i) == C
workingnumber(i) = 12;
elseif workingnumber(i) == D
workingnumber(i) = 13;
elseif workingnumber(i) == E
workingnumber(i) = 14;
else workingnumber(i) = 15;
end
end
end
for i = 1:length(workingnumber)
valueinbase10 = workingnumber(i) * (baseN^(i-1));
finalvalue = finalvalue + valueinbase10;
end
base10number = finalvalue;
end
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!