简体   繁体   中英

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]   
    'ÿ'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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