Number-system conversion in Matlab -
i wrote following program matlab converts numbers decimal-system other systems base 2 (binary) through 16 (hexademical). faced problems when program translates systems, starting base 10. in case remainder must written in way, 10=a, 11=b , on. how possible make it? should use switch-case purpose? thank you!
clc clear dec = input('dec='); n = input('select number system n='); if n>=2 && n<=16 = 0; p=dec; while p>0 dec=p; = + 1; p = fix(dec/n); r = mod(dec, n); base(i) = num2str(r); end base = fliplr(base); disp(['base=' num2str(base)]); else disp('error'); end
this function exists builtin dec2base. if have @ source code via
edit dec2base you see function builds vector of numbers first , uses index character array symbols = '0123456789abcdefg...'. use same approach instead of num2str. base(i) = symbols(r+1) should it.
btw:
- in
displine usingnum2stron string. - instead of using
disp('error'), produce error message viaerror('choose base b 2<=b<=16'). - instead of
base(i)usebase(end+1) = ...rid of variablei.
Comments
Post a Comment