Search code examples
pythonhexdecimalimplicit-conversion

Python convert a string containing hex to actual hex


I have a hex string, but i need to convert it to actual hex. For example, i have this hex string:

3f4800003f480000

One way I could achieve my goal is by using escape sequences:

print("\x3f\x48\x00\x00\x3f\x48\x00\x00")

However, I can't do it this way, because I want create together my hex from multiple variables.

My program's purpose is to:

  1. take in a number for instance 100
  2. multiply it by 100: 100 * 100 = 10000
  3. convert it to hex 2710
  4. add 0000
  5. add 2710 again
  6. add 0000 once more

Result I'm expecting is 2710000027100000. Now I need to pass this hexadecimal number as argument to a function (as hexadecimal).


Solution

  • In Python, there is no separate type as 'hex'. It represents the hexadecimal notation of the number as str. You may check the type yourself by calling it on hex() as:

    #         v  convert integer to hex
    >>> type(hex(123))
    <type 'str'>
    

    But in order to represent the value as a hexadecimal, Python prepends the 0x to the string which represents hexadecimal number. For example:

    >>> hex(123)
    '0x7b' 
    

    So, in your case in order to display your string as a hexadecimal equivalent, all you need is to prepend it with "0x" as:

    >>> my_hex = "0x" + "3f4800003f480000"
    

    This way if you probably want to later convert it into some other notation, let's say integer (which based on the nature of your problem statement, you'll definitely need), all you need to do is call int with base 16 as:

    >>> int("0x3f4800003f480000", base=16)
    4559894623774310400
    

    In fact Python's interpreter is smart enough. If you won't even prepend "0x", it will take care of it. For example:

    >>> int("3f4800003f480000", base=16)
    4559894623774310400
    

    "0x" is all about representing the string is hexadecimal string in case someone is looking/debugging your code (in future), they'll get the idea. That's why it is preferred.

    So my suggestion is to stick with Python's Hex styling, and don't convert it with escape characters as "\x3f\x48\x00\x00\x3f\x48\x00\x00"


    From the Python's hex document :

    Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an index() method that returns an integer.