Skip to content

Instantly share code, notes, and snippets.

@Lablnet Lablnet/hex2dec.cpp
Last active Jan 9, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.