如何将十六进制字符串转换为十六进制数字

时间:2021-06-06 15:45:18

I want to convert a hex string (ex: 0xAD4) to hex number, then to add 0x200 to that number and again want to print that number in form of 0x as a string.

我想将十六进制字符串(例如:0xAD4)转换为十六进制数,然后将0x200添加到该数字,并再次想要以0x的形式打印该数字作为字符串。

i tried for the first step:

我尝试了第一步:

str(int(str(item[1][:-2]),16))

but the value that is getting printed is a decimal string not a hex formatted string (in 0x format) ( i want to print the final result in form of 0x)

但是打印的值是十进制字符串而不是十六进制格式的字符串(0x格式)(我想以0x的形式打印最终结果)

  • [:-2] to remove the last 00 from that number
  • [:-2]从该号码中删除最后一个00

  • item[1] is containing hex number in form of 0x
  • item [1]包含0x形式的十六进制数

3 个解决方案

#1


48  

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

如果您不喜欢开头的0x,请将最后一行替换为

print hex(new_int)[2:]

#2


10  

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

使用带有第二个参数16的int函数将十六进制字符串转换为整数。最后,使用十六进制函数将其转换回十六进制数。

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

相反,你可以直接做

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

#3


-1  

Use format string

使用格式字符串

intNum = 123
print "0x%x"%(intNum)

or hex function.

或十六进制功能。

intNum = 123
print hex(intNum)

#1


48  

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

如果您不喜欢开头的0x,请将最后一行替换为

print hex(new_int)[2:]

#2


10  

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

使用带有第二个参数16的int函数将十六进制字符串转换为整数。最后,使用十六进制函数将其转换回十六进制数。

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

相反,你可以直接做

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

#3


-1  

Use format string

使用格式字符串

intNum = 123
print "0x%x"%(intNum)

or hex function.

或十六进制功能。

intNum = 123
print hex(intNum)