[英]Python: string to hex literal
我想轉換包含十六進制文字的字符串,例如:
s = 'FFFF'
包含文字字符串的十六進制值,如下所示:
h = 0xFFFF
因此,我需要一個函數來進行此轉換。 例如:
h = func('FFFF')
我必須使用什么功能?
int
具有關鍵字選項base
:
In [1]: s = 'FFFF'
In [2]: int(s, base=16)
Out[2]: 65535
如果你想在十六進制形式是實際repr
你的對象的esentation,你需要子類的int
和實施__repr__
:
class Hex(int):
def __new__(cls, arg, base=16):
if isinstance(arg, basestring):
return int.__new__(cls, arg, base)
return int.__new__(cls, arg)
def __repr__(self):
return '0x{:X}'.format(self)
在這里,我還實現了__new__
以使16
(而不是10
)成為默認base
,因此您可以執行以下操作:
>>> Hex('FFFF') # base defaults to 16
0xFFFF
>>> Hex('42', 10) # still supports other bases
0x2A
>>> Hex(65535) # and numbers
0xFFFF
您還必須模擬一個數值類型,以允許將Hex
實例用於加法,減法等(否則,您將只獲得一個普通的int
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.