convert string to hex in python

江枫思渺然 提交于 2019-12-05 01:17:43

Your class.function expects an integer which can be represented either by a decimal or a hexadecimal literal, so that these two calls are completely equivalent:

class.function(0x77)
class.function(119)  # 0x77 == 119

Even print(0x77) will show 119 (because decimal is the default representation).

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:

 >>> int('0x77', 16)
 119

or a decimal one, then parse it as 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.

>>> 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'

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:

>>> print int("0x77", 16)
119

If it doesnt:

>>> print int("119")
119
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!