[英]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.