aboutsummaryrefslogtreecommitdiffstats
path: root/ee2301/baseConvert.cpp
blob: d67574185e1bddbbb6c5ea49d855057414beb454 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// C program to convert a number from any base
// to decimal
#include <stdio.h>
#include <string.h>
#include <iostream>

// To return value of a char. For example, 2 is
// returned for '2'. 10 is returned for 'A', 11
// for 'B'
int val(char c)
{
    if (c >= '0' && c <= '9')
        return (int)c - '0';
    else
        return (int)c - 'A' + 10;
}

// Function to convert a number from given base 'b'
// to decimal
int toDeci(char *str, int base)
{
    int len = strlen(str);
    int power = 1; // Initialize power of base
    int num = 0;   // Initialize result
    int i;

    // Decimal equivalent is str[len-1]*1 +
    // str[len-1]*base + str[len-1]*(base^2) + ...
    for (i = len - 1; i >= 0; i--)
    {
        // A digit in input number must be
        // less than number's base
        if (val(str[i]) >= base)
        {
            printf("Invalid Number");
            return -1;
        }

        num += val(str[i]) * power;
        power = power * base;
    }

    return num;
}

// Driver code
int main()
{
    char str[] = "11A";
    int base = 16;
    printf("Please enter number followed by base: ");
    std::cin >> str >> base;
    printf("Decimal equivalent of %s in base %d is"
           " %d\n",
           str, base, toDeci(str, base));
    return 0;
}