Base convertion without dec2base and base2dec
Show older comments
Good day! I need to create a programm which converts numbers from any base to decimal and from decimal to any base.Without using dec2base,base2dec,dec2bin ,etc.They're working but there is a question. How can I add letters A,B,C,D,E,F there? From decimal:
a=input('number');
b=input('base1');
c=input('base2');
if b==10
i = 1;
q = floor(a/c);
r = rem(a, c);
u(i) = num2str(r(i));
while c <= q
a = q;
i = i + 1;
q = floor(a/c);
r = rem(a, c);
u(i) = num2str(r);
end
u(i + 1) = num2str(q);
u = fliplr(u)
end
u
To decimal:
else
u=0;
for i=1:length(a)
u=u+str2num(a(i))*b^(length(a)-i);
end
1 Comment
There is no need to use loops and the slow num2str or str2num to solve this. Read Andrei Bobrov's solution and see a good example of how to write vectorized code in MATLAB.
Answers (2)
Andrei Bobrov
on 19 May 2015
Edited: Andrei Bobrov
on 19 May 2015
function bs = dec2base_mtx(d,base,l)
%input: d - array, 'base' - base, l -> 'length' numbers in row
ll = ceil(log(max(d(:)))/log(base));
if nargin == 3
ll = max(ll,l);
end
bs = rem(floor(d(:)*base.^(1-ll:0)),base);
function x = base2dec_mtx(bs,base)
% input bs -> array base;
x = bs * base.^(size(bs,2)-1:-1:0).';
example of using
d= [4000; 13; 56000];
base = 16;
bs = dec2base_mtx(d,base);
z = ['0':'9','a':'f'];
bs16 = z(bs+1);
inverse transformation:
z = ['0':'9','a':'f'];
[~,jj] = ismember(bs16,z);
x = base2dec_mtx(jj-1,16);
Walter Roberson
on 19 May 2015
digitcodes = ['0123456789ABCD'};
then, everywhere you have num2str() of a value that is intended to be a separate digit, use digitcodes(value+1) to get the character version of the digit.
Categories
Find more on Lengths and Angles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!