How to add two Hexadecimal numbers? - GeeksforGeeks

27 Jan, 2021
Given two numeric Hexadecimal numbers str1 and str2, the task is to add the two hexadecimal numbers. 
Hexadecimal Number system, often shortened to “hex”, is a number system made up from 16 symbols. it uses 10 symbols from decimal number system which are represented by 0-9 and six extra symbols A – F which represent decimal 10 – 15.
Examples:
Input: str1 = “01B”, str2 = “378”Output: 393Explanation:B (11 in decimal) + 8 =19 (13 in hex), hence addition bit = 3, carry = 11 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 00 + 3 + 0 (carry) = 3, hence addition bit = 3, carry = 001B + 378 = 393
Input: str1 = “AD”, str2 = “1B”Output: C8Explanation:D(13 in Dec) + B(11 in Dec) = 24(18 in hex), hence addition bit = 8, carry = 1A(10 in Dec) + 1 + 1 (carry)= 12 (C in hex), addition bit = C carry = 0AD + 1B = C8  
Approaches: 
Using a map template to find and store the values.
Using inbuilt functions to find the sum.
The idea is to use a map template to store the mapped values that are hexadecimal to decimal and decimal to hexadecimal.
Iterate until one of the given string reaches its length.Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.Perform the same operation on the remaining length of the other string (if both the strings have different lengths).Return the value that has been added.
Iterate until one of the given string reaches its length.
Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.
Perform the same operation on the remaining length of the other string (if both the strings have different lengths).
Return the value that has been added.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Map for converting hexadecimal// values to decimalmap<char, int> hex_value_of_dec(void){    // Map the values to decimal values    map<char, int> m{ { '0', 0 }, { '1', 1 },                      { '2', 2 }, { '3', 3 },                      { '4', 4 }, { '5', 5 },                      { '6', 6 }, { '7', 7 },                      { '8', 8 }, { '9', 9 },                      { 'A', 10 }, { 'B', 11 },                      { 'C', 12 }, { 'D', 13 },                      { 'E', 14 }, { 'F', 15 } };     return m;} // Map for converting decimal values// to hexadecimalmap<int, char> dec_value_of_hex(void){    // Map the values to the    // hexadecimal values    map<int, char> m{ { 0, '0' }, { 1, '1' },                      { 2, '2' }, { 3, '3' },                      { 4, '4' }, { 5, '5' },                      { 6, '6' }, { 7, '7' },                      { 8, '8' }, { 9, '9' },                      { 10, 'A' }, { 11, 'B' },                      { 12, 'C' }, { 13, 'D' },                      { 14, 'E' }, { 15, 'F' } };     return m;} // Function to add the two hexadecimal numbersstring Add_Hex(string a, string b){    map<char, int> m = hex_value_of_dec();    map<int, char> k = dec_value_of_hex();     // Check if length of string first is    // greater than or equal to string second    if (a.length() < b.length())        swap(a, b);     // Store length of both strings    int l1 = a.length(), l2 = b.length();     string ans = "";     // Initialize carry as zero    int carry = 0, i, j;     // Traverse till second string    // get traversal completely    for (i = l1 - 1, j = l2 - 1;         j >= 0; i--, j--) {         // Decimal value of element at a[i]        // Decimal value of element at b[i]        int sum = m[a[i]] + m[b[j]] + carry;         // Hexadecimal value of sum%16        // to get addition bit        int addition_bit = k[sum % 16];         // Add addition_bit to answer        ans.push_back(addition_bit);         // Update carry        carry = sum / 16;    }     // Traverse remaining element    // of string a    while (i >= 0) {         // Decimal value of element        // at a[i]        int sum = m[a[i]] + carry;         // Hexadecimal value of sum%16        // to get addition bit        int addition_bit = k[sum % 16];         // Add addition_bit to answer        ans.push_back(addition_bit);         // Update carry        carry = sum / 16;        i--;    }     // Check if still carry remains    if (carry) {        ans.push_back(k[carry]);    }     // Reverse the final string    // for desired output    reverse(ans.begin(), ans.end());     // Return the answer    return ans;} // Driver Codeint main(void){    // Initialize the hexadecimal values    string str1 = "1B", str2 = "AD";     // Function call    cout << Add_Hex(str1, str2) << endl;}
Time Complexity: O(max(N, M)), where the length of the string first and second is N and M.Auxiliary Space: O(max(N, M)), where the length of the string first and second is N and M.
In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers make use of the hex() function. The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal.
In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers. 
To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. 
To convert the numbers make use of the hex() function. 
The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form.
 Use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal.
Below is the implementation of the above approach:
Python3
# Program to add two hexadecimal numbers. # Driver code# Declaring the variablesstr1 = "1B"str2 = "AD" # Calculating hexadecimal value using functionsum = hex(int(str1, 16) + int(str2, 16)) # Printing resultprint(sum[2:])
Output:
C8
aditya_taparia
base-conversion
Numbers
Hash
Mathematical
Strings
Hash
Strings
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Counting frequencies of array elements
Most frequent element in an array
Double Hashing
Sorting a Map by value in C++ STL
Longest Consecutive Subsequence
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7