Python 如何将十六进制字符串转换为十六进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21879454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a hex string to hex number
提问by RATHI
I want to convert a hex string (ex: 0xAD4) to hex number, then to add 0x200to that number and again want to print that number in form of 0xas 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 numberitem[1]is containing hex number in form of0x
[:-2]从该号码中删除最后一个 00item[1]包含形式为的十六进制数0x
采纳答案by Bach
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 0xin the beginning, replace the last line with
如果您不喜欢0x开头的,请将最后一行替换为
print hex(new_int)[2:]
回答by thefourtheye
Use intfunction with second parameter 16, to convert a hex string to an integer. Finally, use hexfunction to convert it back to a hexadecimal number.
使用int带有第二个参数 16 的函数,将十六进制字符串转换为整数。最后,使用hex函数将其转换回十六进制数。
print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
Instead you could directly do
相反,你可以直接做
print hex(int("0xAD4", 16) + 0x200) # 0xcd4
回答by Kei Minagawa
Use format string
使用格式字符串
intNum = 123
print "0x%x"%(intNum)
or hexfunction.
或hex功能。
intNum = 123
print hex(intNum)

