在python中将字符串转换为十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21669374/
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
convert string to hex in python
提问by Edyoucaterself
I have a script that calls a function that takes a hexadecimal number for an argument. The argument needs to the 0x prefix. The data source is a database table and is stored as a string, so it is returned '0x77'. I am looking for a way to take the string from the database and use it as an argument in hex form with the 0x prefix.
我有一个脚本,它调用一个函数,该函数采用一个十六进制数作为参数。参数需要 0x 前缀。数据源是一个数据库表,存储为字符串,因此返回'0x77'。我正在寻找一种从数据库中获取字符串并将其用作带有 0x 前缀的十六进制形式的参数的方法。
This works:
这有效:
addr = 0x77
value = class.function(addr)
The database entry has to be a string, as most of the other records do not have hexadecimal values in this column, but the values could be changed to make it easier, so instead of '0x77', it could be '119'.
数据库条目必须是一个字符串,因为大多数其他记录在此列中没有十六进制值,但可以更改这些值以使其更容易,因此它可以是“119”而不是“0x77”。
采纳答案by bereal
Your class.functionexpects an integerwhich can be represented either by a decimal or a hexadecimal literal, so that these two calls are completely equivalent:
您的class.function期望一个整数,其可以通过一个十进制或十六进制来表示文字,从而使这两个调用是完全等效的:
class.function(0x77)
class.function(119) # 0x77 == 119
Even print(0x77)will show 119(because decimal is the default representation).
Evenprint(0x77)会显示119(因为十进制是默认表示)。
So, we should rather be talking about converting a string representation to integer. The string can be a hexadecimal representation, like '0x77', then parse it with the base parameter:
因此,我们应该谈论将字符串表示形式转换为integer。该字符串可以是十六进制表示,如'0x77',然后使用基本参数解析它:
>>> int('0x77', 16)
119
or a decimal one, then parse it as int('119').
或十进制一,然后将其解析为int('119').
Still, storing integer whenever you deal with integers is better.
尽管如此,在处理整数时存储整数会更好。
EDIT: as @gnibbler suggested, you can parse as int(x, 0), which handles both formats.
编辑:正如@gnibbler 建议的那样,您可以解析为int(x, 0),它可以处理两种格式。
回答by icedtrees
>>> hex(119)
'0x77'
#or:
>>> hex(int("119"))
'0x77'
This should work for you.
这应该对你有用。
You can also get the hex representation of characters:
您还可以获得字符的十六进制表示:
>>> hex(ord("a"))
'0x61'
回答by Guy Sirton
I think you're saying that you read a string from the database and you want to convert it to an integer, if the string has the 0x prefix you can convert it like so:
我想你是说你从数据库中读取了一个字符串,你想把它转换成一个整数,如果字符串有 0x 前缀,你可以像这样转换它:
>>> print int("0x77", 16)
119
If it doesnt:
如果没有:
>>> print int("119")
119

