/*************************************************************************
* dec2base.c
* 05.03.2003 Chris Schuster <cs_1@gmx.de>
* convert decimal numbers to BASE numbers
* ./dec2base [BASE] Number
*
* COMPILATION:
* bash$ cc -o dec2base dec2base.c -lm -Wall
*************************************************************************/

#include <stdio.h>
#include <math.h> //Lib Math required when compiling
#include <stdlib.h>

#define DEFAULT_BASE 16

int main (int argc, char ** argv)
{

	long int num, base;

	base = DEFAULT_BASE;

	if (argc == 3) {
		num = atoi(argv[2]);

		if (atoi(argv[1]) > 1 && atoi(argv[1]) < 37) //MAX Base: Nums 0-9+ Chars A-Z
			base = atol(argv[1]);
		else
			printf("base out of bounds: using base %d\n", DEFAULT_BASE);

	}
	else if (argc == 2)
		num = atoi(argv[1]);
	else {
		fprintf(stderr, "Please supply valid arguments.\nUsage %s [BASE] number\n", argv[0]);
		return -1;
	}


	{ // required so we can declare the size correctly
		/*
		One byte = 1111 1111b = 2^8d = 256d possible values = c
		Num possibilities c for Base b is b^x (where is x is the num of digits)
		The num of possibilities and b and c are known,
		so we get	 c = b^x
				256d = 16d^x
				x = log16d(256d)
				x = log (256d) / log (16d);
		=> num of digits is CEIL( log (2d^(num bits) ) / log (16d) );
	*/
		char hex[ (int) ceil ( log( pow(2, 8*sizeof(long int)))  /  log (base) ) ];
		int i = 0;

		//printf("%d\n", (int)ceil ( log( pow(2,8*sizeof(long int)))  /  log (base) ));

		while (num > 0) {

			if ((num % base) < 10)
				hex[i++] = '0' + num % base;
			else
				hex[i++] = 'A'+ num % base -10;

			num = num / base;
		}

		while (i>0) //output reverse FABC => CBAF
			putchar(hex[--i]);

		printf("\n");
		return 0;
	}
}
