-1

I have an issue with my program which is used to calculate addition and subtraction for Hexadecimals. The algorithm of my program is:

  • Take 2 strings inputted by the user, and "+" or "-" depending on the operator they chose
  • Convert the 2 strings into decimals, and add or subtract
  • If the second number is bigger, use the bigger number to subtract the smaller number, and put a "-" in front of it when returning the result (1 - 8 should = -7, but instead, I take 8 - 1 = 7, and return "-" and "7" so it gives "-7)
  • Take the decimal result from the operation and convert back to hexadecimal
  • Return string of hexadecimal

However, I have run into a issue where my calculations give me wrong answers. (For e.g FFFFFF + FFFFFFFFFF prints "FFFFFFE" instead of "10000FFFFFE")

What can I do to solve the issue?

I created my own Power function for this program as I need a a number that can go up to 16 Fs for the Hexadecimal string.

Power Function:

unsigned long long int result = 1;
int i;

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

return result;

Code:

int i;
int power = FirstHexaNumber.length() - 1;
int power2 = SeconHexaNumber.length() - 1;
int checkLength = FirstHexaNumber.length();
int checkLength2 = SeconHexaNumber.length();
unsigned long long int decimalNumber = 0;
unsigned long long int decimalNumber2 = 0;
unsigned long long int totalDecimal;
int temporary;
string result;

if (Operator == '+')                            //check if operator is add or minus
{
    //Convert Hex to Decimal for first number

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

            decimalNumber += ((int(FirstHexaNumber[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(FirstHexaNumber[i]) >= 65 && int(FirstHexaNumber[i]) <= 70)    // check if FirstHexaNumber is A to F
        {
            decimalNumber += ((int(FirstHexaNumber[i])) - 55)*powerFunc(16, power);
        }
        else if (int(FirstHexaNumber[i]) >= 97 && int(FirstHexaNumber[i]) <= 102)   // check if FirstHexaNumber is a to f
        {
            int x = powerFunc(16, power);
            decimalNumber += ((int(FirstHexaNumber[i])) - 87)* x;
        }
        power--;            //power-- since it starts from "HexaNumber.length - 1". Power should decrease as assignment of power goes down
    }

    //Convert Hex to Decimal for second number

    for (i = 0; i < checkLength2; i++)
    {
        if (int(SeconHexaNumber[i]) >= 48 && int(SeconHexaNumber[i]) <= 57) {

            decimalNumber2 += ((int(SeconHexaNumber[i])) - 48) * powerFunc(16, power2);     //formula to convert Hexadecimal to Decimal
        }
        else if (int(SeconHexaNumber[i]) >= 65 && int(SeconHexaNumber[i]) <= 70)
        {
            decimalNumber2 += ((int(SeconHexaNumber[i])) - 55)*powerFunc(16, power2);       //formula to convert Hexadecimal to Decimal
        }
        else if (int(SeconHexaNumber[i]) >= 97 && int(SeconHexaNumber[i]) <= 102)
        {
            unsigned long long int x = powerFunc(16, power2);
            decimalNumber2 += ((int(SeconHexaNumber[i])) - 87)*x;       //formula to convert Hexadecimal to Decimal
        }
        power2--;
    }

    totalDecimal = decimalNumber + decimalNumber2;                                  //Adds the total decimal to convert into hexadecimal

    if (totalDecimal == 0)
    {
        return "0";
    }

    //Converts Decimal to Hexadecimal
    for (i = 0; totalDecimal != 0; i++)             //as long as totalDecimal does not hit 0 from being divided by 16, run the loop
    {
        temporary = totalDecimal % 16;              //use temporary as a variable to temporarily hold onto the number remainder of mod 16

        if (temporary >= 10)                        //if temporary >= 10, that means it needs to be converted to alphabet
        {
            result.insert(0, 1, temporary + 55);    //result.insert inserts a string of text into a spot, and pushes everything else backwards.
        }                                           //in this case, result.insert assigns "temporary+55" into the spot of characters 0 to 1.

        else                                        //else, it means that the decimal will be a number, add 48 to convert to ascii          
        {
            result.insert(0, 1, temporary + 48);
        }
        totalDecimal = totalDecimal / 16;           //divide by 16 to move on to finding the next digit/alphabet
    }

    return result;
}
else if (Operator == '-')                           //check if operator is add or minus
{
    //Convert Hex to Decimal for first number

    for (i = 0; i < checkLength; i++)               //as long as the loop does not exceed the length of the hexadecimal, run it
    {
        if (int(FirstHexaNumber[i]) >= 48 && int(FirstHexaNumber[i]) <= 57) {

            decimalNumber += ((int(FirstHexaNumber[i])) - 48) * powerFunc(16, power);
        }
        else if (int(FirstHexaNumber[i]) >= 65 && int(FirstHexaNumber[i]) <= 70)
        {
            decimalNumber += ((int(FirstHexaNumber[i])) - 55)*powerFunc(16, power);
        }
        else if (int(FirstHexaNumber[i]) >= 97 && int(FirstHexaNumber[i]) <= 102)
        {
            decimalNumber += ((int(FirstHexaNumber[i])) - 87)*powerFunc(16, power);
        }
        power--;    
    }

    //Convert Hex to Decimal for second number

    for (i = 0; i < checkLength2; i++)
    {
        if (int(SeconHexaNumber[i]) >= 48 && int(SeconHexaNumber[i]) <= 57) {

            decimalNumber2 += ((int(SeconHexaNumber[i])) - 48) * powerFunc(16, power2);
        }
        else if (int(SeconHexaNumber[i]) >= 65 && int(SeconHexaNumber[i]) <= 70)
        {
            decimalNumber2 += ((int(SeconHexaNumber[i])) - 55)*powerFunc(16, power2);
        }
        else if (int(SeconHexaNumber[i]) >= 97 && int(SeconHexaNumber[i]) <= 102)
        {
            decimalNumber2 += ((int(SeconHexaNumber[i])) - 87)*powerFunc(16, power2);
        }
        power2--;
    }

    if (decimalNumber >= decimalNumber2)
    {
        totalDecimal = decimalNumber - decimalNumber2;          //subtract bigger number by smaller number.

        if (totalDecimal == 0)
        {
            return "0";
        }

        for (i = 0; totalDecimal != 0; i++)
        {
            temporary = totalDecimal % 16;

            if (temporary >= 10)
            {
                result.insert(0, 1, temporary + 55);
            }
            else
            {
                result.insert(0, 1, temporary + 48);
            }
            totalDecimal = totalDecimal / 16;
        }

        return result;
    }
    else
    {
        totalDecimal = decimalNumber2 - decimalNumber;          //subtract bigger number by smaller number.

        if (totalDecimal == 0)
        {
            return "0";
        }

        for (i = 0; totalDecimal != 0; i++)
        {
            temporary = totalDecimal % 16;

            if (temporary >= 10)
            {
                result.insert(0, 1, temporary + 55);
            }
            else
            {
                result.insert(0, 1, temporary + 48);
            }
            totalDecimal = totalDecimal / 16;
        }

        return "-" + result;
    }

}
return 0;
2
  • 2
    You're not converting the numbers into decimal. You're converting a hexadecimal string into an integer type, which is stored in binary. Also, your code contains tons of magic numbers, which makes your code hard to read and debug. Instead of using the ASCII values in your conditions, use character literals like 'A'. That way, you don't need comments to tell you what those numbers mean.
    – eesiraed
    Commented Jul 14, 2018 at 4:17
  • Stack Overflow isn't a free debugging service, and you should show your attempts at debugging the code with a debugger or other simpler methods such as debug print statements. You can also test each part of the code separately to figure out exactly which part of the code is causing the problem, and make a minimal reproducible example. This won't be the only time you end up with a bug in your code, and learning to debug your programs will help you much more than having someone find the bug for you. idownvotedbecau.se/nodebugging
    – eesiraed
    Commented Jul 14, 2018 at 4:17

2 Answers 2

3

You can try this snippet:

int a,b;
cout << "\nEnter A in hex: ";
cin >> hex >> a;
cout << "\nEnter B in hex: ";
cin >> hex >> b;
cout << "\n Addition of " << hex << a <<" and "<< hex << b << " is " << hex << a+b;
cout << "\n Substraction of " << hex << a << " and " << hex << b << " is " << hex << a - b;
3
  • but what if I have to return the hex instead of couting?
    – M. Meek
    Commented Jul 14, 2018 at 4:42
  • @M.Meek: store it as int x = a+b;
    – seccpur
    Commented Jul 14, 2018 at 5:13
  • 1
    @M.Meek Direct the result into an std::stringstream by adding std::stringstream ss and replacing cout with ss. Then, get the string with ss.str().
    – eesiraed
    Commented Jul 14, 2018 at 18:33
2

int x = powerFunc(16, power); should be long long x = powerFunc(16, power); Don't know full source of the function pow, the return type should be long long too.

Hexadecimal Calculator can be more simple.

#include <sstream>
std::stringstream ss1(s1),ss2(s2);
ss1 >> std::hex >> i1;
ss2 >> std::hex >> s2;

std::cout << std::hex << std::uppercase << i1 + s2 << std::endl;

std::stringstream res;
res << std::hex << std::uppercase << i1 + i2;
return res.str();
2
  • would there be a way where i can use std::hex and assign it to a string and return that string?
    – M. Meek
    Commented Jul 14, 2018 at 4:43
  • std::stringstream res; res<<std::hex<<i1+i2<<std::endl;return res.str();
    – martian
    Commented Jul 14, 2018 at 4:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.