1

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?

Juan Garcia
  • 843
  • 2
  • 11
  • 34
  • possible duplicate of [Convert hex string to int in Python](http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python) – muddyfish Jul 24 '15 at 09:28
  • What are you *actually* trying to achieve? You can't store a *"literal"* in a name, you store the object it represents. – jonrsharpe Jul 24 '15 at 09:32

2 Answers2

4

int has a keyword option base:

In [1]: s = 'FFFF'

In [2]: int(s, base=16)
Out[2]: 65535
galath
  • 5,717
  • 10
  • 29
  • 41
  • Ok. What I want is FFFF in var, not 65535, how I can perform this? – Juan Garcia Jul 24 '15 at 09:29
  • 1
    @jgd that doesn't make conceptual sense. `65535` **is** `0xFFFF`, they are just two different literal forms of the same object (which is really stored in binary somewhere in your computer's memory), but you will always see the integer `repr` form when you e.g. `print` it. If you want the *string* `'0xFFFF'` you can use `hex`. – jonrsharpe Jul 24 '15 at 09:30
0

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

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437