在Python中,我们可以使用bin()
或format()
将整数转换为二进制字符串表示形式。
print(bin(1)) # 0b1
print(bin(-1)) # -0b1
print(bin(10)) # 0b1010
print(bin(-10)) # -0b1010
print("{0:b}".format(10)) # 1010
print("{0:#b}".format(10)) # 0b1010 , with 0b prefix
print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits
print(format(10, "b")) # 1010
print(format(10, "#b")) # 0b1010, with 0b prefix
print(format(10, "b").zfill(16)) # 0000000000001010, pad zero, show 16 bits
# with hex, oct bin
# int: 10; hex: a; oct: 12; bin: 1010
result = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(10)
print(result)
# with 0x, 0o, or 0b as prefix:
# int: 10; hex: 0xa; oct: 0o12; bin: 0b1010
result = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(10)
print(result)
参考文献
翻译自: https://mkyong.com/python/python-how-to-convert-int-to-a-binary-string/