0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's probably important to pay lip service to endianness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.