Light Bulb
Light Bulb

Reputation: 11

How to convert network hex string to integer in python

I have a hexadecimal string which I have received from internet (SSL client). It is as follows: "\x7f\xab\xff". This string is actually the length of something. I need to calculate the integer value of a sub-string in the above string (based on starting and ending position). How do I do that.

I tried struct.pack and unpack. It did not work I tried doing a split based on \x, and that gave some UTF error I tried converting the string to a raw string. Even that did not work

    r"\xff\x7f".replace('\x' , '')

    SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
    position 0-1: truncated \xXX escape


    >>> "\xff\x7f"[1]   
    '\x7f'
    >>> "\xff\x7f"[0]   
    'ÿ'


    >>> "\xff\x7f"[1]
    '\x7f'
    >>> "\xff\x7f"[0]   
    'ÿ'

Upvotes: 0

Views: 106

Answers (1)

Gershom Maes
Gershom Maes

Reputation: 8170

The following worked for me:

>>> str_val = r'\xff\x7f'
>>> int_val = int(str_val.replace('\\x', ''), 16)
>>> int_val
65407

Don't forget that the backslash character is literally appearing in the string. So to target it, you need to declare '\\x', not just '\x'!

Note that this also assumes the 1st octet, '\xff', is higher/more significant than the second, '\x7f'. It's possible the source of this value wants you to treat the second value as the more significant one.

Upvotes: 1

Related Questions