function s = convbase( number, base )

% ----------------------------------------------------------------------
% Jonathan R. Senning <jonathan.senning@gordon.edu>
% Gordon College
% Written: January 21, 1999
% Revised: September 7, 2000
% Revised: January 24, 2007
%
% $Id: convbase.m,v 1.3 2007/01/24 17:22:21 senning Exp senning $
%
% Usage: s = convbase( n, b )
%
% Returns:
%       s:      A string representing the number in the base b
%
% Parameters:
%       n:      The decimal number to convert
%       b:      The desired base (must be between 2 and 36, inclusive)
%
% This function accepts a decimal number and and returns the string
% representation of the number in the specified base.  This function
% only converts to bases between (inclusive) base-2 and base-36.  It
% uses the convention that hexidecimal numbers use of using alphabetic
% letters to represent values larger than 9.
% ----------------------------------------------------------------------

digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

% If number is nonpositive...

if ( number <= 0 ) || ( base - floor( base ) != 0 )
    s = 'number must be positive';
    return;
end

% Make sure base is in required range...

if ( base < 2 ) || ( base > 36 )
    s = 'base must be between 2 and 36 inclusive';
    return
end

% Get the integer and fractional parts of the number, and initialize string
% that will contain the string representation of the converted number.

integer_part = floor( number );
fractional_part = number - integer_part;
s = '';

% Convert the integer part.  This is done according to the algorithm
% given on page 47 of "Numerical Mathematics and Computing", Fourth Edition,
% by Cheney and Kincaid, Brooks/Cole, 1999.  Basically we repeatedly divide
% the integer part by the new base, remembering the remainders of each
% division.

while ( integer_part > 0 )
    x = integer_part / base;
    integer_part = floor( x );
    s = strcat( digits( 1 + round( base * ( x - integer_part ) ) ), s );
end

% If there is a fractional part then we need to append a radix point.

if ( fractional_part > 0 )
	s = strcat( s, '.' );
end

% Convert the fractional part.  See pages 48 and 49 Cheney and Kincaid.
% The idea is to repeatedly multiply the fractional part by the new base,
% remembering (and then removing) the integer part of the product.

length_of_decimal = 0;
while ( fractional_part > 0 ) && ( length_of_decimal < 400 / base )
    length_of_decimal = length_of_decimal + 1;
    fractional_part = fractional_part * base;
    x = floor( fractional_part );
    s = strcat( s, digits( 1 + x ) );
    fractional_part = fractional_part - x;
end

% Finally, append the base as a "subscript" separated from the number
% by an underscore.

s = sprintf( '%s_%d', s, base );

end
