Skip to content
Related Articles

Related Articles

Python Program to add two hexadecimal numbers

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 09 Aug, 2022
View Discussion
Improve Article
Save Article

Given two hexadecimal numbers, write a Python program to compute their sum.

Examples:

Input: a = "01B", b = "378" 
Output: 393 
Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, 
             carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, 
             carry = 0 0 + 3 + 0 (carry) = 3, hence addition bit = 3, 
             carry = 0 01B + 378 = 393 
Input: a = "AD", b = "1B" 
Output: C8 
Explanation: D(13 in Dec) + B(11 in Dec) = 24(18 in hex), 
              hence addition bit = 8, carry = 1 A(10 in Dec) + 1 + 1 (carry)= 12 (C in hex), 
              addition bit = C carry = 0 AD + 1B = C8

Approach:

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 we will 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. We will also 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 are the implementations based on the above approach:

Example 1:

Python3




# Python program to add two hexadecimal numbers.
 
# Driver code
# Declaring the variables
a = "01B"
b = "378"
 
# Calculating hexadecimal value using function
sum = hex(int(a, 16) + int(b, 16))
 
# Printing result
print(sum[2:])

Output

393

Example 2:

Python3




# Python program to add two hexadecimal numbers.
 
# Driver code
# Declaring the variables
a = "B"
b = "C"
 
# Calculating hexadecimal value using function
sum = hex(int(a, 16) + int(b, 16))
 
# Printing result
print(sum[2:])

Output

17

Example 3:

Python3




# Python program to add two hexadecimal numbers.
 
# Driver code
if __name__ == "__main__" :
 
    # Declaring the variables
    a = "01B"
    b = "378"
     
    # Calculating hexadecimal sum by using hex() and int()
    hexadecimal_sum = lambda a,b : hex(int(a, 16) + int(b, 16))
     
    # calling hexadecimal_sum lambda function
    print(hexadecimal_sum(a,b)[2:])

Output

393

Method: Using “add” operator

Python3




from operator import*
num1="01B"
num2="378"
print(hex(add(int(num1,16),int(num2,16))))

Output

0x393

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!