16进制字符串转10进制整数:
1 2 3 4 5 6 7 8 9 10 |
>>> int(0xff) 255 >>> int('0xff') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '0xff' >>> int('0xff',16) 255 >>> long(0x55) 85L |
10进制整数转16进制字符串:
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> hex(15) '0xf' >>> hex(15L) '0xfL' >>> hex('15') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: hex() argument can't be converted to hex >>> hex('15',10) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: hex() takes exactly one argument (2 given) |
整数转为2进制字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> bin(15) '0b1111' >>> bin(15L) '0b1111' >>> bin(0x15) '0b10101' >>> bin('0x15') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object cannot be interpreted as an index >>> bin('0x15', 16) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bin() takes exactly one argument (2 given) |
转成8进制字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
>>> oct(76) '0114' >>> oct(7) '07' >>> oct(8) '010' >>> oct(76L) '0114L' >>> oct(7L) '07L' >>> oct(8L) '010L' >>> oct('76') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: oct() argument can't be converted to oct >>> oct('76',16) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: oct() takes exactly one argument (2 given) |
总结一点: 各种进制的字符串不能直接转成别的进制的字符串, 要先用int()或long()转成整数后,再转为字符串。
str —-X—->str
str—->int—->str