1

I am trying to write a method for converting hexadecimal words to signed integers. I want to use python 2-7. In python3 I can do the following

def word2int(hex_str):
    ba = bytes.fromhex(hex_str)
    return int.from_bytes(ba,byteorder='big',signed=True)

However, neither of these methods (i.e. fromhex and from_bytes) are defined in python 2-7. Are there any nice and simple methods of doing this in Python 2-7?

1

1 Answer 1

2

Use int to convert to an unsigned integer, and then manually convert to signed.

def word_to_int(hex_str):
    value = int(hex_str, 16)
    if value > 127:
        value = value-256
    return value
Sign up to request clarification or add additional context in comments.

1 Comment

Can't believe I didn't think of that! Seems to work for 16-bit strings as well, only with -65534 instead of -256.

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.