Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hex string from signed integer

Tags:

python

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?

like image 395
Ellery Newcomer Avatar asked Oct 23 '08 06:10

Ellery Newcomer


People also ask

Which method converts an integer to a hexadecimal string?

An integer can be converted to a hexadecimal by using the string. ToString() extension method. int. Parse − Converts the string representation of a number to its 32-bit signed integer equivalent.

Does Atoi work on hex?

atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.

How do you parse a hex string in Python?

Use base=16 as a second argument of the int() function to specify that the given string is a hex number. The int() function will then convert the hex string to an integer with base 10 and return the result.


2 Answers

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:]
like image 193
paxdiablo Avatar answered Oct 19 '22 23:10

paxdiablo


Try this function:

'%#4x' % (-1 & 0xffffffff)
like image 23
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 22:10

Ignacio Vazquez-Abrams