简体   繁体   English

Python:字符串转换为十六进制文字

[英]Python: string to hex literal

I want to convert string that contains hex literal, for example: 我想转换包含十六进制文字的字符串,例如:

s = 'FFFF'

to hex value that contains literal string, like this: 包含文字字符串的十六进制值,如下所示:

h = 0xFFFF

So, I need a function to make this conversion. 因此,我需要一个函数来进行此转换。 For example: 例如:

h = func('FFFF')

What function I have to use? 我必须使用什么功能?

int has a keyword option base : int具有关键字选项base

In [1]: s = 'FFFF'

In [2]: int(s, base=16)
Out[2]: 65535

If you want the hex form to be the actual repr esentation of your object, you would need to sub-class int and implement __repr__ : 如果你想在十六进制形式是实际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)

Here I have also implemented __new__ to make 16 (rather than 10 ) the default base , so you can do things like: 在这里,我还实现了__new__以使16 (而不是10 )成为默认base ,因此您可以执行以下操作:

>>> Hex('FFFF')  # base defaults to 16
0xFFFF
>>> Hex('42', 10)  # still supports other bases
0x2A
>>> Hex(65535)  # and numbers
0xFFFF

You will also have to emulate a numeric type to allow Hex instances to be used in addition, subtraction, etc. (otherwise you'll just get a plain int back). 您还必须模拟一个数值类型,以允许将Hex实例用于加法,减法等(否则,您将只获得一个普通的int )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM