0

So, as part of an assignment, I wrote a program to convert hexadecimal to decimal. But I was not able to get the desired result. Can someone please pin point the error in this code?

#include<bits/stdc++.h>
#include<math.h>
using namespace std;

int hexaToDecimal(string n){
    int ans = 0;
    int power =1;
    int s = n.size();

    for(int i=s-1; i>=0; i--){
        if(n[i] >= '0' && n[i] <= '9'){
            ans = ans + power*(n[i]);
        }
        else if(n[i] >= 'A' && n[i] <= 'F'){
            ans = ans + power*(n[i]-'A' + 10);
        }
        power = power * 16;
    }
    return ans;
}

        


int main(){
    string n;
    cin>>n;
    cout<<hexaToDecimal(n)<<endl;
    return 0;
}
amaan211
  • 15
  • 4

3 Answers3

1

Simpler way to go about it:

unsigned fromHex(const string &s) { 
    unsigned result = 0;
    for (char c : s) 
        result = result << 4 | hexDigit(c);
    return result;
}

unsigned hexDigit(char c) { 
    return c > ‘9’ ? c - ‘A’ + 10: c - ‘0’;
}
Kostas
  • 3,822
  • 11
  • 28
0

You may add - '0' like - 'A'. There is the code:

#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int hexaToDecimal(string n){
    int ans = 0;
    int power =1;
    int s = n.size();

    for(int i=s-1; i>=0; i--){
        if(n[i] >= '0' && n[i] <= '9'){
            ans = ans + power*(n[i] - '0'); //THERE.
        }
        else if(n[i] >= 'A' && n[i] <= 'F'){
            ans = ans + power*(n[i]-'A' + 10);
        }
        power = power * 16;
    }
    return ans;
}

        


int main(){
    string n;
    cin>>n;
    cout<<hexaToDecimal(n)<<endl;
    return 0;
}

Changes only near //THERE.

  • yeah it works now but i couldnt get the logic behind it. – amaan211 Nov 02 '20 at 06:12
  • When you using '0' or 'A' like int, is not '0' = 0, it is '0' = 48 (ASCII code). For example, you have '5'. '5' = 53, '0' = 48, '5' - '0' = 53 - 48 = 5. The same thing with A, B, C, etc. – GRAPHITE9932 Nov 02 '20 at 06:22
0

Here is a different approach on how to solve your problem. You could use std::hex which is defined in the headerfile #include<iostream> Which is a simpler way to do it.

For Example:

#include <iostream>


int main()
{
    int HexNum;
    std::cin >> std::hex >> HexNum;
    std::cout << HexNum << std::endl;

    return 0;
}

Output:

10F
271
Geno C
  • 1,305
  • 3
  • 6
  • 22
  • Good but kind of defeats the purpose of the assignment, don't you think? – Kostas Nov 02 '20 at 15:52
  • @Kostas - Yes and no. I think this is a pretty sweet answer because it makes use of what is in the header file and it's simple and straight to the point. I like your answer as well +1 for the simplicity. – Geno C Nov 02 '20 at 21:16