Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Greetings,

I currently have run into an issue that I seem to not understand even while debugging. I am trying to create a hexadecimal to decimal converter program, but I've run into a problem that I can't fix. Every time I try to input 8Fs or higher to convert into decimal, it ends up giving 16Fs' result (aka the max range:18446744....615)

This is the code:
C++
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int powerFunc(int x, int y)
{
	unsigned long long int result = 1;
	int i;

	for (i = 0; i < y; i++)
	{
		result *= x;
	}

	return result;
}

int hexToDec(string hexaNumber)
{
	int i;
	int power = hexaNumber.length() - 1;
	int checkLength = hexaNumber.length();
	unsigned long long int decimalResult = 0;

	//Convert Hexa to Decimal for Number;

	for (i = 0; i < checkLength; i++)
	{
		if (int(hexaNumber[i]) >= '0' && int(hexaNumber[i]) <= '9') {				// check if FirstHexaNumber 0 to 9

			decimalResult += ((int(hexaNumber[i])) - 48) * powerFunc(16, power);	//formula to convert hexadecimal into decimal, int(FirstHexaNumber[i]) is used to convert hexa into a number
		}
		else if (int(hexaNumber[i]) >= 'A' && int(hexaNumber[i]) <= 'F')			// check if FirstHexaNumber is A to F
		{
			decimalResult += ((int(hexaNumber[i])) - 55)*powerFunc(16, power);
		}
		else if (int(hexaNumber[i]) >= 'a' && int(hexaNumber[i]) <= 'f')			// check if FirstHexaNumber is a to f
		{
			decimalResult += ((int(hexaNumber[i])) - 87)*powerFunc(16, power);
		}
		power--;			//power-- since it starts from "HexaNumber.length - 1". Power should decrease as assignment of power goes down
	}

	return decimalResult;
}

int main()
{
	unsigned long long int result;
	unsigned long long int dec1;
	unsigned long long int dec2;
	unsigned long long int totalDec;
	string hexa1;

	string FirstHexaNumber;

	getline(cin, FirstHexaNumber);

	dec1 = hexToDec(FirstHexaNumber);

	cout << dec1 << endl;
	

	return 0;
}


What I have tried:

I have tried debugging the issue, the power function works fine, it manages to get the result it should get. In this case, when I input "FFFFFFFF", the power I get is 268435456, which is correct.

However, when it gets to the converting part, it messes up. For some reason, on the first run on the for loop for the formula, (int(F) - 55) * 16^8 = it ends up giving 18446744....615. What can I do to solve this issue? Thanks in advance.
Posted
Updated 13-Jul-18 22:08pm

1 solution

powerFunc returns an int:
int powerFunc(int x, int y)
{
   ...
}
and 16^8 is 4,294,967,296 or in hex 0x100000000 - which doesn't fit in a 32 bit integer!
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900