0

I want to convert any value (that can be negative or positive) into hex. My current method does this.

The read value in this example is 4003.

workingline = stringdb.readline().split(";")
print hex(int(workingline[0]))

This returns

0xfa3

It should be:

0xa30f0000

(Padded with zeros and inverted hexadecimal) IF the value is negative it should be:

0xFEFFFFFF

With the value -2.

I assume padding does not help in this case.

Thank you!

1

1 Answer 1

4

You want the struct module:

>>> struct.pack("<I", 4003).encode('hex')
'a30f0000'

For -2, you'll need to do some other work:

>>> struct.pack("<I", -2 + 2**32).encode('hex')
'feffffff'

A way to do it for any value is:

struct.pack("<I", (value + 2**32) % 2**32).encode('hex')
Sign up to request clarification or add additional context in comments.

3 Comments

This appears to only work for positive values. Do you know another means to make it work for negative values as well?
Alright, thank you! I suppose I will just make a IF statement for two methods. :)
Using "<i" instead of "<I" does the right thing without the + 2**32.

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.