为了将整数转换为二进制、八进制或十六进制的文本串,可以分别使用bin() ,oct() 或hex() 函数:
>>> x = 1234 >>> bin(x) '0b10011010010' >>> oct(x) '0o2322' >>> hex(x) '0x4d2'
如果你不想输出0b , 0o 或者0x 的前缀的话,可以使用format() 函数
>>> format(x, 'b') '10011010010' >>> format(x, 'o') '2322' >>> format(x, 'x') '4d2'
整数是有符号的,所以如果你在处理负数的话,输出结果会包含一个负号
>>> x = -1234 >>> format(x, 'b') '-10011010010' >>> format(x, 'x') '-4d2'
如果你想产生一个无符号值,你需要增加一个指示最大位长度的值。比如为了显示32 位的值,可以像下面这样写:
>>> x = -1234 >>> format(2**32 + x, 'b') '11111111111111111111101100101110' >>> format(2**32 + x, 'x') 'fffffb2e'
为了以不同的进制转换整数字符串,简单的使用带有进制的int() 函数即可
>>> int('4d2', 16) 1234 >>> int('10011010010', 2) 1234