Python程序将两个十六进制数相加
给定两个十六进制数,编写一个Python程序来计算它们的和。
例子:
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
方法:
要在Python中添加两个十六进制值,我们首先将它们转换为十进制值,然后将它们相加,最后再次将它们转换为十六进制值。为了转换数字,我们将使用hex()函数hex( )函数是 Python3 中的内置函数之一,用于将整数转换为其相应的十六进制形式。我们还将使用int()函数将数字转换为十进制形式。 Python和 Python3 中的int()函数将给定基数中的数字转换为十进制。
下面是基于上述方法的实现:
示例 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:])
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:])
输出:
393
示例 2:
蟒蛇3
# 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:])
输出:
17