简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM