c++c++11visual-c++c++14number-systems

hexa-decimal to decimal conversion (using implicit type casting)


I think there's some problem in my vs code I am new to this coding stuff even after writing the correct code it gives me wrong results in almost every second code I write i get uncertain results Plz guys help me with this , plz check running this code in your machine....

#include <iostream>
using namespace std;
int main()
{

    char a[30];
    cout << "enter the hexadecimal";
    cin >> a;
    int i = 0, c, digit, decimal = 0, p = 1;
    while (a[i] != '\0') {
        i++;
    }
    for (int j = i; j >= 0; j--) {
        c = a[j];
        if (c >= 48 && c <= 57) {
            digit = c - 48;
        }
        else if (c >= 97 && c <= 112) {
            digit = c - 87;
        }
        decimal += digit * p;
        p *= 8;
    }
    cout << "\ndecimal is " << decimal;
    return 0;
}

while entering hexa decimal plz only enter small alphabets i have not taken capital letters into consideration

for cheking hexadecimal to decimal use this site https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=146


Solution

  • There are several problems with the code, but I think that the main one is that you are multiplying p by 8 when it should be 16 (as hex is base-16, not base-8).

    You also should take care with invalid inputs. What happens if someone enters an invalid letter 'j' for instance?

    Besides, when you calculate the initial length of the string, you are setting ito the position of the array with a '\0' value so when you start processing the input, a[i] is 0 and that leads to using an uninitialized variable (digit has not been assigned a value, this is related to the previous "invalid input" issue).

    By the way, I would also use chars in the comparisions instead of ASCII codes, it's easier to see what you are looking for:

        if (c >= '0' && c <= '9') {
            digit = c - '0';
        }
    

    and so on...