I have some Perl code where the hex() function converts hex data to decimal. How can I do it on Python?
3 Answers
If by "hex data" you mean a string of the form
s = "6a48f82d8e828ce82b82"
you can use
i = int(s, 16)
to convert it to an integer and
str(i)
to convert it to a decimal string.
8 Comments
Eric
For a negative hex number, this don't work.
Sven Marnach
@EricWang This works perfectly fine for negative numbers: ideone.com/IHOQvp. Unless you have a negative number encoded in fixed-width two's complement format, but that would be a different problem than what was asked here. (Hint: use the
struct module in that case.)arcolife
hex -> decimal -> binary -> decimal:
int(bin(int(hex(42), 16)), 2)Chris Stratton
Beware that this is a big endian interpretation. That would be suitable for some things (many network protocols for example are big endian) but not for others, like looking at internal program data from the current majority of systems which are natively little endian.
Chris Stratton
On the contrary, it is actually quite common to encounter data that has already been rendered as human readable hex, which contains little endian numeric values. So no, the comment is not misleading in the slightest. Python gets used not only in comprehensive all-python solutions, but very heavily for processing the output and logs of other systems and gluing test rigs together.
|
You could use a literal eval:
>>> ast.literal_eval('0xdeadbeef')
3735928559
Or just specify the base as argument to int:
>>> int('deadbeef', 16)
3735928559
A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:
>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100
hexconverts a hex string to an integer value (which is stored internally in binary but is essentially simply a numeric value without a base). The call toprintconverts that value into a decimal string and prints it.