Convert.c

From ChekMate Security Group

/*
convert.c
1.0
 Copyright (C) 2006 Joshua D. Abraham (jabra@ccs.neu.edu)

 This program is released under the terms of the GNU General Public License
 (GPL), which is distributed with this software in the file "COPYING".
 The GPL specifies the terms under which users may copy and use this software.



    Name: (c) Josh Abraham
    Date: November 2004
    Purpose: convert a number in a given base to another base
*/
#include <stdio.h>
#include <math.h>
int atoi(char s[]);
void printd(int num, int outBase);
int convertToDec(char *num, int inBase);
int power(int x, int y);
int main(int argc, char *argv[])
{
	int i, num, inBase, outBase;
	char *num2;
	if (argc!=4)
	{
		printf("Usage: ./convert numberToConvert, outBase, inBase");
	    return 1;
	}	
	inBase=atoi(argv[2]);
	outBase=atoi(argv[3]);
	if (inBase < 2 || inBase > 36)
	{
		printf("inBase needs to be a number between 2 and 36");
		return 2;
	}
	if (outBase < 2 || outBase > 36)
	{
		printf("outBase needs to be a number between 2 and 36");
		return 3;
	}
	num2=argv[1];
	num=convertToDec(argv[1], inBase);
	printd(num, outBase);
	printf("\n\n");
	return 0;
}
//printd: displays the given num in a given base
void printd(int num,int outBase)
{
	int rem,quot;
	quot=num/outBase;
	
	rem=num%outBase;
	if (quot>0)
		printd(quot, outBase);
	if(rem>=10)
		rem+=('A'-'0'-10);
	printf("%c", rem+'0');
}
//convertToDec: converts the array into dec
int convertToDec(char *num, int inBase){
	int len,sum=0,i,tmp;
	len=strlen(num);
	char c;
	for(i=len-1;i>=0;i--){
		if(num[i]>='a' && num[i]<='z')
			c=num[i]-'a'+10; 
		else
			c=num[i]-'0';
		tmp = c* power( inBase, (len-i-1) );
		sum+=tmp;
	}
	return sum;
}
// power: returns the int value of x raised to a given y 
int power(int x, int y){
	int p;
	for(p=1;y>0;--y)
		p*=x;
	return p;
}
/* atoi: converts s to integer*/
int atoi(char s[])
{
	int i, n;
	n=0;
	for(i=0; s[i] >= '0' && s[i] <= '9'; ++i)
		n=10 * n + (s[i] - '0');
	return n;
}