The goal of my program is to take in 2 inputs - one for the base, and one for the number (which should be of that base type). It will then do a
calculation and print out the number in base 10 form. For instance,
Input Output
========== ======
10 1234 1234
8 77 63 (the value of 77 in base 8, octal)
2 1111 15 (the value of 1111 in base 2, binary)
So far, I've been able to do everything except successfully take a numerical input in - I can't think of a way to take individual numbers from a character array and store it into an integer array so that my equations will work properly =\
/*
1. Read in 2 inputs: base and number
2. Convert the number to the specified base
3. Print the results
*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void to_bin(int *, int, int);
void to_oct(int *, int, int);
void to_dec(int *, int);
int pow(int, int);
int main(void)
{
int base, i = 0;
int num[SIZE] = {0};
char input[SIZE], *ptr;
puts("Enter a base number (2, 8, 10):");
scanf("%d", &base);
puts("Enter a number:");
scanf("%s", &input);
ptr = input;
while (*ptr != '\0')
{
num[i] = *ptr;
ptr++;
i++;
}
if (base == 2)
to_bin(num, i, base);
if (base == 8)
to_oct(num, i, base);
if (base == 10)
to_dec(num, i);
return 0;
}
void to_bin(int *num, int i, int base)
{
int sum = 0, n = 0;
for (;i >= 0; i--)
{
if (num[i] != 0)
sum += pow(n, base);
n++;
}
printf("%d\n", sum);
}
void to_oct(int *num, int i, int base)
{
int sum = 0, n = 0;
for (;i >= 0; i--)
{
if (num[i] != 0)
sum += (num[i] * pow(n, base));
n++;
}
printf("%d\n", sum);
}
void to_dec(int *num, int i)
{
int cnt;
for (cnt = 0; cnt <= i; cnt++)
printf("%d", num[cnt]);
puts("");
}
int pow(int n, int base)
{
int cnt, tot = 1;
for (cnt = 0; cnt < n; cnt++)
tot *= base;
return tot;
}