23

Say I have the classic 4-byte signed integer, and I want something like

print hex(-1)

to give me something like

0xffffffff

In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.

So.. is there a way to do it?

4 Answers 4

36

This will do the trick:

>>> print(hex (-1 & 0xffffffff))
0xffffffff

or, a variant that always returns fixed size (there may well be a better way to do this):

>>> def hex3(n):
...     return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011

Or, avoiding the hex() altogether, thanks to Ignacio and bobince:

def hex2(n):
    return "0x%x"%(n&0xffffffff)

def hex3(n):
    return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
Sign up to request clarification or add additional context in comments.

3 Comments

Don't rely on the 'L' suffix, it is going away in Python 3.0 so hex2 will chop off a digit. The %x formatting operator is generally a better bet than hex().
Incorporated comment and Ignacios option below into accepted answer (and gave Ignacio an upvote)
Please, replace return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:] by return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:]))[-8:]
4

Try this function:

'%#4x' % (-1 & 0xffffffff)

Comments

2

Use

"0x{:04x}".format((int(my_num) & 0xFFFF), '04x')

where my_num is the required number.

Comments

2

Another way is to convert the signed integer to bytes first with int.to_bytes, then convert the bytes to a hex string with bytes.hex:

print((-1).to_bytes(4, signed=True).hex())

Output:

ffffffff

The reverse (hex string to signed integer): Hex string to signed int in Python

Comments

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.