Adding Hexadecimals

I have to write a program to perform addition of two hexadecimal number each with up to 10 Digits. If the result of the addition is more than 10 Digits long, then it needs to output "Addition Overflow".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>                                                             
#include <string>
#include <cctype>   
#include <cmath>                                                           
using namespace std;
const int SIZE = 10;

long long int convertToDec(char a[], const int size);

int main()
{
    char a[SIZE], a2[SIZE], ans; 
    signed long long int hex_1 = 0 , hex_2 = 0;
   // char sum[16], ans[16] ; 
    
    do
    {
        cout << "Enter Two 10 Digit Hexadecimal numerals for this program to apply Addition\n(Hexadecimals are from 0~9 and A~F)\n";
        cout << "Please Enter your first 10 Digit Hexadecimals(keep them at 10 Digits ): \n";
        
       // for(int i = 0; i< SIZE; i++)
        //{
           cin >> a[SIZE]; 
        //}
        //cout << "Now Enter the Second 10 Digit Hexadecimal: \n";
        //for(int j =0; j< SIZE; j++)
        //{
        //   cin >> a2[j];
        //}
        
        hex_1 = convertToDec(a, SIZE);
        hex_2 = convertToDec(a2, SIZE);
        
        //sum[16] = hex_1 + hex_2; 
        
        cout << hex_1 << " " << endl;
        
       
    }while(ans=='y' || ans=='Y');
    cout << "See you Next Time!!\n";
    system("PAUSE");
    return 0;
}
long long int convertToDec(char a[], const int size)
{
  signed long long int sum = 0, total = 0 ;
  float count = 0; 
   int i = 0, hex[size]; 
   for(int i =0; i < size; i++)
   {
      if(a[i] >= '0' && a[i] <='9')
      {
         hex[i] = a[i] - '0';
      }
      else if(toupper(a[i]) >= 'A' && toupper(a[i]) <='F')
      {
         hex[i] = a[i] - 'A' + 10;
      }
      else
      {
         hex[i] = -1; 
      }
      
   }
       for(int j=9; j >= 0 ; j--) 
   {
      sum = sum + ((hex[j] * pow(16, count)));
      cout << " Hex: "<< sum << endl; 
      count++; 
   } 
   return sum; 
}


SO Far My program could Convert From Hex to Integers and my problem is I don't know what to do next.
Why are you even bothering to do all that , just set the basefield flag as std::hex.
This is an Extra Credit Assignment.. And We have to keep it withing materials we've learned
So please provide me some hint if you can?
Hi All,
After you do that(i mean after converting them to int) take sum of them and then again convert it to hex, now, to know is the number more than 10 digits.
you can cast it to string and then check that what is the length of string , But there is more easy ways ,But now i have headache and can not display them.
Have Nice Life.
Just a quick comment on style and approach. Function convertToDec is misnamed, as it converts from a hex string to an integer. The integer isn't a decimal value (internally the computer works in binary).

Within the function, the pow() function is using a sledgehammer to crack a walnut. Bear in mind that internally the function will usually calculate the logarithm, multiply by the power, then calculate the antilogarithm (with possible rounding errors). That's an awful lot of work when you could achieve the same goal with a single multiplication by 16 on each pass through the loop.

The rest of the code as has already been said, will need to add the two integers (one line of code) and then convert back to hex afterwards - with a check for overflow beyond 10 hex digits.

(I was going to point out that the integer may be up to 41 bits long, but you've already got that covered with the use of long long int).

Edit
- just noticed this : cin >> a[SIZE];
That looks horribly wrong, first it is reading a single character rather than a string, and secondly it is storing the result outside the boundaries of the array.
Valid subscripts are in the range 0 to SIZE-1. a[SIZE] is one position past the end of the array.

Also if the user enters an invalid hex character, at line 61 there is hex[i] = -1; which looks like it silently ignores the bad data. I think it should either stop processing the string at that point, and/or output an error message. Perhaps the strings should first be validated and the user prompted to try again, before proceeding with the conversion to an integer.
Last edited on
Yeah.. I'm still a bit lost here
Well, i wrote quite a lot in my previous post. A one-line response doesn't help us to help you. Perhaps you could explain specifically what you need help with.
Okay I fixed the cin >> a[SIZE]; TO cin >> a[i];

- Currently I need help with how to add these numbers after converting to int and then checking if it is 10 digits long to Output the warning.

Edit:
This hint was given to us, but I still can't put my hands on it.
1
2
3
4
5
6
7
8
9
Add2 numbers and deter
mine the remainder. Remainder exists and is carried
over if number exceeds 15, or F.
18 = x + y; // x and y values from above example
18 % 16 = 2;
18 / 16 = 1; // 1 is our remainder
12 = (1 * 10) + 2
This method converts 18 in decimal to 12 in
hexadecimal 
Last edited on
Your solution can be broken to these steps.
1. Input the hex numbers and convert to an integer. Done.
1
2
3
4
5
//pseudo code
cin >> hex1str;
cin >> hex2str;
long long num1=hexToInt(hex1str);
long long num2=hexToInt(hex2str);

2. Add the numbers.(very trivial)
 
long long sum=num1+num2;

3. Convert the sum to hex and check for overflow.
1
2
char hexSum[SIZE+1];
bool isOverflow = intToHex(hexSum,sum);

Like hexToInt , but the reverse.
Here's a sample implemention.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool intToHex(char *outstr,long long in)//outstr must be atleast 11 bytes (or 'char's long)
{
    outstr[10]=0;//null terminator
    const char ciphers[] = "0123456789abcdef";
    for(int i=SIZE-1;i>=0;--i)
    {                            //here, we convert using the long division method.
        outstr[i]=ciphers[in%16];//<- Add the remainder
        in/=16;                  //<- set 'in' to the quotient
    }
    if(in)
        return true;//overflow
    else
        return false;
}

4. Output.

Hope that helps.
P.S. Your hexToDec() function can be revamped (or reimplemented a little).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
long long int hexToInt(char a[],int size)
{
    //assert(size <= SIZE)
    const char ciphers[] = "0123456789abcdef";
    long long sum = 0,m=1;
    for(int i = size-1 ; i>= 0 ; --i)
    {
        /*
        strchr() returns the pointer to the first occurrence of a[i].
        We subtract that pointer from the base pointer to get the index and thus the value of the given cipher.
        */
        int hexdigit = strchr(ciphers,a[i])-ciphers;
        sum += hexdigit*m;
        m*=16;
    }
    return sum;
}
Last edited on
Topic archived. No new replies allowed.