Python Program to add two hexadecimal numbers
Last Updated :
16 Dec, 2023
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:
Method 1:
Python3
a = "01B"
b = "378"
sum = hex ( int (a, 16 ) + int (b, 16 ))
print ( sum [ 2 :])
|
Method 2:
Python3
a = "B"
b = "C"
sum = hex ( int (a, 16 ) + int (b, 16 ))
print ( sum [ 2 :])
|
Method 3:
Python3
if __name__ = = "__main__" :
a = "01B"
b = "378"
hexadecimal_sum = lambda a,b : hex ( int (a, 16 ) + int (b, 16 ))
print (hexadecimal_sum(a,b)[ 2 :])
|
Time complexity: O(1)
Space complexity: O(1)
Method 4: Using “add” operator
Python3
from operator import *
num1 = "01B"
num2 = "378"
print ( hex (add( int (num1, 16 ), int (num2, 16 ))))
|
Output
0x393
Time complexity: O(1)
Space complexity: O(1)
Method 5: Using manual addition of hexadecimal digits: This approach performs the addition manually by adding the digits of the two hexadecimal strings from right to left and carrying over as necessary. It also takes care of adding leading zeroes to make the two strings of equal length.
Steps:
- Get two hexadecimal numbers as input strings.
- Make the two input strings of equal length by adding leading zeroes.
- Initialize carry as 0 and an empty string as the result.
- For each position from right to left:
- Convert the two digits at that position to integers using the int() function.
- Add the two integers and the carry, and compute the sum and the new carry.
- Convert the sum to a hexadecimal digit using the hex() function and append it to the result string.
- If there is a carry after the last addition, convert it to a hexadecimal digit and prepend it to the result string.
- Return the result string as the sum of the two hexadecimal numbers.
Python3
def add_hexadecimal(a, b):
n = max ( len (a), len (b))
a = a.zfill(n)
b = b.zfill(n)
carry = 0
result = ""
for i in range (n - 1 , - 1 , - 1 ):
digit_sum = int (a[i], 16 ) + int (b[i], 16 ) + carry
digit = hex (digit_sum % 16 )[ 2 :]
carry = digit_sum / / 16
result = digit + result
if carry:
result = hex (carry)[ 2 :] + result
return result
a = "01B"
b = "378"
print (add_hexadecimal(a, b))
|
Time Complexity: The time complexity of this approach is O(n), where n is the length of the longer hexadecimal string. This is because we have to iterate over each digit of the two strings once to add them together.
Space Complexity: The space complexity of this approach is O(n), where n is the length of the longer hexadecimal string. This is because we are creating a new string of length n to hold the sum of the two strings.
Method 6: Using reduce():
Algorithm:
- Import the reduce() function from the functools module.
- Define a function add_hex that takes two hexadecimal strings a and b as input.
- Use a list comprehension to convert the input strings to a list of decimal integers.
- Use the reduce() method to sum the list of decimal integers element-wise.
- Convert the resulting decimal sum to a hexadecimal string using the built-in hex() function.
- Use slicing to remove the “0x” prefix from the output string.
- Return the resulting hexadecimal string.
- Call the add_hex() function with sample input values “B” and “C”.
- Print the output of the function call, which should be the sum of the two input values in hexadecimal format.
Python3
from functools import reduce
def add_hex(a, b):
decimal_sum = reduce ( lambda x, y: x + y, [ int (x, 16 ) for x in [a, b]])
return hex (decimal_sum)[ 2 :]
a = "B"
b = "C"
print (add_hex(a, b))
|
The time complexity : O(n), where n is the number of input hexadecimal digits. This is because the list comprehension iterates over the input strings once, and the reduce() method also iterates over the resulting list of decimal integers once.
The space complexity : O(n), because the list comprehension creates a new list of decimal integers that is the same size as the input strings, and the reduce() method also creates a temporary variable to store the accumulated sum. However, since the size of the input strings is typically small, the space complexity of this implementation is not a concern.
Similar Reads
Python program to add two binary numbers
Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum become
4 min read
How to Add Two Numbers in Python - Easy Programs
The task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12. Using the "+" Operator+ operator is the simplest and most direct way to add two numbers . It perfor
5 min read
Python program to add two Octal numbers
Given two octal numbers, the task is to write a Python program to compute their sum. Examples: Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175Approach: To add two octal values in python we will first convert them into decimal values then add them and then finally aga
2 min read
Python program to add two matrices
Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Outp
2 min read
Python Program to Multiply Two Binary Numbers
Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined funct
2 min read
Python Program to Convert Decimal to Hexadecimal
In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. Method 1: Using hex() function hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Syntax : h
3 min read
Python program to convert float decimal to Octal number
Python doesn't support any inbuilt function to easily convert floating point decimal numbers to octal representation. Let's do this manually. Approach : To convert a decimal number having fractional part into octal, first convert the integer part into octal form and then fractional part into octal f
3 min read
Python Program to Subtract Two Binary Numbers
We are given two binary numbers, num1 and num2 and we have to subtract these two binary numbers and return the result. In this article, we will see how we can subtract two binary numbers in Python. Examples: Input: a = "1110" , b = "0110"Output: "1000"Explanation: We can see that when "1110" is subt
3 min read
Python program to print the hexadecimal value of the numbers from 1 to N
Given a number N, the task is to write a Python program to print the hexadecimal value of the numbers from 1 to N. Examples: Input: 3 Output: 1 2 3 Input: 11 Output: 1 2 3 4 5 6 7 8 9 a bApproach: We will take the value of N as input.Then, we will run the for loop from 1 to N+1 and traverse each "i"
5 min read
Python Program to calculate sum and average of three numbers
We are given three numbers, and our task is to calculate the sum and average of these numbers. The average of the numbers is defined as the sum of the given numbers divided by the total number of elements. In this case, it will be the sum of given three numbers divided by 3. Example: Input: 10, 20,
3 min read