

/*************************************************************************
	
	file created on:	2002/11/12   22:00
	filename: 			BaseConverter.h
	author:				Andreas Hartl<andy@runicsoft.com>

		visit http://www.runicsoft.com for updates and more information

	purpose:	Three utility functions to convert between number bases:

	ChangeLog:
		- 2002/11/13: rewritten ConvertToBase: now ca. 25% faster


	USAGE:

    void ConvertToBase ( char* str, int base, int num ) :

		 converts <num> to a number of base <base> and stores result 
		 in str


	int  ConvertFromBase ( char* str, int base ) :

		 converts the number of base <base> given by <str>
		 to base 10 and returns as an int
	

	void ConvertBetweenBases ( char* output, char* input, 
							   int outputbase, int inputbase ) :

		 converts the number of base <inputbase> given in <input>
		 to a number of base <outputbase> and stores the result in
		 <output>

NOTE:	for practical reasons it makes only sense to convert up to 
		base 36 since there are only 36 useful 
		number identifiers ( 10 ciphers + 26 letters ) and e.g.
		36 in base 37 would result in the ASCII char after Z ( '[' ) ...

**************************************************************************/


#ifndef BASECONVERTER_H_
#define BASECONVERTER_H_


#include <stdio.h>
#include <string.h>
#include <math.h>



void ConvertToBase ( char* str, const int base, int num )
{
	int x = 0;
	int nmd;
	while ( num  )
	{
		nmd = num % base;
		str[x++] = nmd <= 10 ? '0' + nmd : 'A'-10 + nmd;
		num /= base; 
	}

	str[x] = 0;
	_strrev (str);
}


int ConvertFromBase ( char* str, int base )
{
	int x = 0;
	_strrev(str);
	for ( int c = 0; c < (int)strlen(str); c++ )
	{
		if ( str[c] - '0' <= 10 )
			x += (int) pow ( base, c ) * ( str[c] - '0' );
		else
			x += (int) pow ( base, c ) * ( str[c] - 'A' + 10 );
	}
	return x;
}



void ConvertBetweenBases ( char* output, char* input, int outputbase, int inputbase )
{
	ConvertToBase ( output, outputbase, ConvertFromBase ( input, inputbase ) );
}



#endif
