ilaunchpad
ilaunchpad

Reputation: 1313

Python hex to int conversion error

>>> print(int(0x51))

81

This is correct.

>>> str = 51
>>> cmd = "0x%s" %(str)
>>> print(int(cmd))

But why is this incorrect? I get ValueError: invalid literal for int() with base 10: '0x51'

Upvotes: 1

Views: 3909

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

0x51 is a Python integer literal, it itself already produces an integer:

>>> 0x51
81

See the Integer and long integer literals documentation for the details; this is the hexinteger form. Calling int() on that integer object just returns the same integer value again.

You can use int() on a string with the prefix 0x, but you need to tell it to use 0 as the base:

>>> int('0x51', 0)
81

0 is a special case here; it tells int() to look for Python integer literal prefixes such as 0x to determine the real base from that. From the int() documenation:

Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.

Upvotes: 9

Related Questions