%file name: dec2bin.m %Written by Dr. James S. Kang, Cal Poly Pomona. %Convert decimal number to binary number. %x = input decimal number. %y = output binary number. %To run the program, try % >>dec2bin(19) function[y] = dec2bin(x) if x==0 NB=1; else NB=ceil(log(x)/log(2)); end if exp(NB*log(2))-floor(exp(NB*log(2)))<0.5 NA=floor(exp(NB*log(2))); else NA=ceil(exp(NB*log(2))); end if x==NA NB=NB+1; end if x==NA b(NB) = 1; else if floor(x/(2^(NB-1))) == 1 b(NB) = 1; else b(NB) = 0; end end if NB>1 & x>0 for k = 1:NB-1 sum = 0; for j=1:k sum=sum+b(NB-j+1)*2^(NB-j); end if floor((x-sum)/2^(NB-1-k))==1 b(NB-k)=1; else b(NB-k)=0; end end end for k=1:NB y1(k)=b(NB+1-k); end y=y1';