function z = num2bin(x,dotrim) %z = num2bin(x,dotrim) %Convert floating point numbers in x to %binary format. x must be finite and numeric %Trim trailing zeros in string fraction if dotrim ~= 0 %Its inverse operation is found in bin2num. % >x = pi; % >s = num2bin(x) % s = % % +.11001001000011111101101010100010001000010110100011000*2^+2 % >z = bin2num(s) % z = % % 3.14159265358979 % >z==x % ans = % 1 %October 7, 2000, Herman Gollwitzer if nargin < 2 dotrim = 0; end if ~(isa(x,'double') & all(isfinite(x))) error('All data must be finite and numeric.') end x = x(:); n = length(x); fracbits = 53;%# of bits for IEEE double fraction nummask = (x ~= 0);%non-zero numbers frac = repmat('0',n,fracbits); expo = zeros(n,1); %Work with the non-zero elements if any(nummask) [f,e] = log2(abs(x(nummask))); frac(nummask,:) = dec2bin(pow2(f,fracbits)); expo(nummask,:) = e; end %Build the string rep of x if dotrim %Remove trailing zeros in fraction representation mask = (frac == '0'); %Calculate number of trailing zeros in each row. %Use fracbits-1 in min so that zero is handled properly. trailzed = 1+fracbits - min(fracbits-1,sum(cumprod(fliplr(mask),2),2)); for k = 1:n %Replace trailing zeros with blanks frac(k,trailzed(k):end) = blanks(1); end z = strcat('+.',frac,repmat('*2^',n,1),num2str(expo,'%+1i')); % strcat ignores the trailing padding. else% represent to full length z = strcat(repmat('+.',n,1),frac,repmat('*2^',n,1),num2str(expo,'%+1i')); end z((x < 0),1) = '-';%Sign adjustment for mantissa