Skip to content

Instantly share code, notes, and snippets.

@lablnet
Last active January 9, 2019 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lablnet/77a2094ce36e673e8851b830cff87e04 to your computer and use it in GitHub Desktop.
Save lablnet/77a2094ce36e673e8851b830cff87e04 to your computer and use it in GitHub Desktop.
Convert hexa to decimal
#include <iostream>
#include <string.h>
using namespace std;
int hex2dec(string str);
int power(int exponent, int base);
int count(string s);
int main ()
{
string hexa;
cout << "Enter HEXA number to convert into decimal \t";
cin >> hexa;
cout << "Decimal is => " << hex2dec(hexa);
return 0;
}
int hex2dec(string hexa)
{
int len,i,decimal = 0,exp = 0;
len = count(hexa) - 1;
for (i = len; i >= 0; i--){
if (hexa[i] <= '9' && hexa[i] >= '0'){
decimal += (hexa[i] - 48) * (power(16,exp));
}
if (hexa[i] <= 'F' && hexa[i] >= 'A') {
decimal += (hexa[i] - 55) * power(16,exp);
}
exp++;
}
return decimal;
}
int count (string s)
{
int count = 0;
while (s[count] != '\0') {
count ++;
}
return count;
}
int power(int base, int exponent)
{
int result = 1;
while (exponent != 0){
result *= base;
--exponent;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment