Code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*This handles up to B64*/
#define B10MAXVAL 100
void convertToBase(int, int, char [], int);
char toChar(int);
char ans;
void swapspace(char []);
int main()
{
for (;;) // why doesnt this loop work ?
{
char value[B10MAXVAL];
int input = 0;
int base = 10;
/*using scanf %[*][width][modifiers]type*/
printf("Please enter the number you wish to convert:\n");
scanf("%d", &input);
fflush(stdin);
printf("Please enter the base you want to convert to:\n");
scanf("%d", &base);
fflush(stdin);
convertToBase(base, input, value, 0);
printf("%d converted to base-%d is %s", input, base, value);
// getchar();
printf("\n\nDo you wish to run my aswesome program again Y/N?");
ans = getchar();
ans = getchar ();
if (ans=='N' || ans=='n')
break;
}
printf("\n");
system("PAUSE");
return 0;
}
void convertToBase(int base, int number, char outputstring[], int i) {
/*do this by repeatedly dividing and taking the modulus (remainder). */
int r = 0;
int result = 0;
if (number == 0) {
/*Making sure there is no 0*/
outputstring[i] = 0x30;
outputstring[i+1] = 0;}
/*Divide using mod operator until 0 is reached*/
r = number % base;
if(((number-r) == 0)&& ((number - r)!= number)) {
outputstring[i] = toChar(r);
outputstring[i + 1] = 0;}
else if (((number - r) == number)){
outputstring[i] = toChar(number-1);
outputstring[i + 1] = 0; }
else {
outputstring[i] = toChar(r);
convertToBase(base, ( (number-r)/base ), outputstring, (i+1));
/*call swapspace, recursion owns, one of many options, reverse iteration
or copy_backwards algo in C++ library*/
}
if (i == 0) {
swapspace(outputstring);}
}
char toChar(int i){
char alphabet[] = {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z','+','/','='};
return alphabet[i];
}
void swapspace(char string[]){
/*Because we're adding in the wrong direction, we need to swap the order of our value*/
int i = 0;
int x = 0;
char *original;
/*here we allocate memory and determine the size of the space needed with
then we move the string into original, then we free the stack*/
original = (char*)malloc(sizeof(char) * (strlen(string) + 1));//Leave room for null 0
strcpy(original, string);
x = strlen(string);
while (i < x){
string[i] = original[(x-1) - i]; //-1 to kill null zero
i++;
}
string[i] = 0;
free(original);
}