File: ef230-2023-08/www/examples/base_conversion.m Download
%! Convert a number from one base to another
%! Supports decimals, bases up to 36, only positive numbers
% University of Tennessee : Will Schleter

function main
clear all; clc;
cvtbase('10.5',10,16);
cvtbase('37',10,32);
cvtbase('lazydog',26,10);
return

function r = cvtbase(str,b1,b2)
if b1>36 || b1<2
    fprintf('Invalid base %d\n\n',b1);
    return;
end
if b2>36 || b2<2
    fprintf('Invalid base %d\n\n',b2);
    return;
end

chars = '0123456789abcdefghijklmnopqrstuvwxyz';
tolp = 4;

n=0;
dec = strfind(str,'.');
if isempty(dec)
    dec = length(str)+1;
end
pow = dec -2 ;
for ii=1:length(str)
    if ii ~= dec
        p = find(str(ii)==chars)-1;
        if p>=b1 || p<1
            fprintf('Input string has invalid character "%s" at position %u\n\n',str(ii),ii);
            return;
        end
        n = n + p .* b1 .^ pow;
        pow = pow -1;
    end
end
r = '';
num = fix(n);
while num > 0
    num2 = fix(num./b2);
    rem = num - num2.*b2;
    r = [chars(rem+1) r];
    num = num2;
end

num = n - fix(n);
if num ~=0
    r = [r '.'];
end
ii=0;
while num~=0 && ii<tolp
    num2 = fix(num.*b2);
    rem = num - num2./b2;
    r = [ r  chars(num2+1)];
    num = rem.*b2;
    ii = ii + 1;
end
fprintf('%s converted from base %u to base %u is %s\n\n',str,b1,b2,r);
return