[英]Python 3 - Convert 2-digit Integers to and from 2 character Hex Equivalent
I have researched this and while I could find some methods to convert a string consisting of a 3-digit integer to a string consisting of its 2-digit hex equivalent, I did not find a way to convert the 2-digit-hex string back into the original 3-digit integer. 我已经对此进行了研究,虽然我可以找到一些方法来将由3位整数组成的字符串转换为由2位十六进制等效项组成的字符串,但我没有找到将2位十六进制字符串转换回的方法转换为原始的3位整数。
For example, I would like to convert "015" to its 2-digit hex equivalent "0F" and vice versa. 例如,我想将“ 015”转换为其等效的2位数十六进制“ 0F”,反之亦然。
Another example: "123" to "7B" and "7B" to "123". 另一个示例:“ 123”至“ 7B”和“ 7B”至“ 123”。
I would prefer separate methods for these two conversions, rather than 1 function that can take either type of string and return the other. 对于这两次转换,我希望使用单独的方法,而不是使用一种可以采用任何一种字符串类型并返回另一种类型的函数。
# Method I'm currently using to convert int to hex:
myHex = str(format(int(myNumber), '02x'))
print("Integer " + myNumber + " converted to " + myHex)
Your help is greatly appreciated. 非常感谢您的帮助。
you can use: 您可以使用:
1) build in hex method 1)内置十六进制方法
hex(int('123')) --> '0x7b'
str(int('0x7b', 16)) --> '123'
if you do not want '0x' part: 如果您不希望使用“ 0x”部分:
hex(int('123'))[2:] --> '7b'
str(int('7b', 16)) --> '123'
or : 要么 :
2) using fstring 2)使用fstring
def str_to_hex(my_str_num):
return f'{int(my_str_num):02x}'
def hex_to_str(my_hex):
return f'{int(my_hex, 16):>03}'
print(str_to_hex('015'))
print(hex_to_str('0f'))
print(str_to_hex('123'))
print(hex_to_str('7b'))
output: 输出:
0f
015
7b
123
You can use the following function: 您可以使用以下功能:
def two_digit_hex_to_three_digit_integer(hex):
return str(int(hex, 16)).zfill(3)
Explanation: 说明:
int(hex, 16)
will convert your two-digit hex number into an int of base 10. Then, this will be converted to str
, and it will be filled with up to 3 zeros to satisfy the condition you said of three-digit integer. int(hex, 16)
会将您的两位数十六进制数转换为以10为底的int值。然后,将其转换为str
,并用最多3个零填充,以满足您所说的三位数条件整数。
Usage: 用法:
>>> two_digit_hex_to_three_digit_integer('7B')
'123'
>>> two_digit_hex_to_three_digit_integer('0F')
'015'
For base-10
to base-16
conversion you can harness str
formatting following way: 对于
base-10
到base-16
转换,您可以通过以下方式利用str
格式:
def convert_dec_to_hex(value):
return "%X" % int(value)
print(convert_dec_to_hex("123")) # 7B
uppercase X
gives ABCDEF
and lowercase x
gives abcdef
so 大写字母
X
给出ABCDEF
,小写字母x
给出abcdef
因此
def convert_dec_to_hex(value):
return "%X" % int(value)
print(convert_dec_to_hex("123")) # 7b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.