How to get hex string from signed integer

16

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?

python
asked on Stack Overflow Oct 23, 2008 by Ellery Newcomer • edited Aug 15, 2020 by azro

3 Answers

27

This will do the trick:

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

or, in function form (and stripping off the trailing "L"):

>>> def hex2(n):
...     return hex (n & 0xffffffff)[:-1]
...
>>> print hex2(-1)
0xffffffff
>>> print hex2(17)
0x11

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:]
answered on Stack Overflow Oct 23, 2008 by paxdiablo • edited Oct 23, 2008 by paxdiablo
4

Try this function:

'%#4x' % (-1 & 0xffffffff)
answered on Stack Overflow Oct 23, 2008 by Ignacio Vazquez-Abrams • edited Mar 23, 2012 by Somnath Muluk
1

"0x{:04x}".format((int(my_num) & 0xFFFF), '04x') , where my_num is the required number

answered on Stack Overflow Sep 14, 2016 by Sai Gautam

User contributions licensed under CC BY-SA 3.0