Skip to content

Instantly share code, notes, and snippets.

@mikhailnov
Last active May 21, 2019 17:45
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 mikhailnov/ea61a55ffcdd87ce2228e88ce4117671 to your computer and use it in GitHub Desktop.
Save mikhailnov/ea61a55ffcdd87ce2228e88ce4117671 to your computer and use it in GitHub Desktop.
C++ program to convert hexadecimal to decimal
// C++ program to convert hexadecimal to decimal
#include <iostream>
#include <string.h>
#include <cmath>
using namespace std;
// Function to validate input data
int validateInput(string hexVal)
{
int result = 0;
int len = hexVal.size();
if (len < 1) {
cout << "Empty input?\n";
result = 0;
} else {
result = 1;
}
// now validate every symbol of the line
for (int i=0; i<len; i++) {
// convert to uppercase for further operation with uppercase
hexVal[i] = toupper(hexVal[i]);
//cout << hexVal[i];
if (!(((floor(hexVal[i]) == ceil(hexVal[i])) /* check if is integer */
&& (hexVal[i] >= '0' && hexVal[i] <= '9')) /* if is integer, check value */
|| ((isalpha(hexVal[i])) /* if is a latin letter */
&& (hexVal[i] >= 'A' && hexVal[i] <= 'F')) )) { /* check that it is A-F */
cout << hexVal[i] << " is an invalid character for a hexademical number!\n";
result = 0;
break;
}
}
return result;
}
// Function to convert hexadecimal to decimal
int hexadecimalToDecimal(string hexVal)
{
int len = hexVal.size();
// Initializing base value to 1, i.e 16^0
int base = 1;
int dec_val = 0;
// Extracting characters as digits from last character
for (int i=len-1; i>=0; i--)
{
// if character lies in '0'-'9', converting
// it to integral 0-9 by subtracting 48 from
// ASCII value.
if (hexVal[i]>='0' && hexVal[i]<='9')
{
dec_val += (hexVal[i] - 48)*base;
// incrementing base by power
base = base * 16;
}
// if character lies in 'A'-'F' , converting
// it to integral 10 - 15 by subtracting 55
// from ASCII value
else if (hexVal[i]>='A' && hexVal[i]<='F')
{
dec_val += (hexVal[i] - 55)*base;
// incrementing base by power
base = base*16;
}
}
return dec_val;
}
int main()
{
string hexNum;
cout << "Enter input number:\n";
getline(cin, hexNum);
if (!validateInput(hexNum)) {
cout << "Error\n";
return 1;
} else {
cout << hexadecimalToDecimal(hexNum) << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment