Juan Garcia
Juan Garcia

Reputation: 855

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?

Upvotes: 1

Views: 3278

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122024

If you want the hex form to be the actual representation of your object, you would need to sub-class int and implement __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:

>>> 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).

Upvotes: 0

galath
galath

Reputation: 5965

int has a keyword option base:

In [1]: s = 'FFFF'

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

Upvotes: 4

Related Questions