在Python中,我们可以使用bin()
或format()
将整数转换为二进制字符串表示形式。
print(bin(1)) # 0b1print(bin(-1)) # -0b1print(bin(10)) # 0b1010print(bin(-10)) # -0b1010print("{0:b}".format(10)) # 1010print("{0:#b}".format(10)) # 0b1010 , with 0b prefixprint("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bitsprint(format(10, "b")) # 1010print(format(10, "#b")) # 0b1010, with 0b prefixprint(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)
参考文献:
- Python bin文件
- Python格式文件
- Python格式规范迷你语言
每日一课 | 如何将String转换为int
每日一课 | Python time.sleep 精准延迟到秒
每日一课 | Python 如何判断一个字符串是否包含另一个字符串?
球分享
球点赞
![4bb740d437f0300dc7e904cf3176f56d.png](https://i-blog.csdnimg.cn/blog_migrate/b181f564fa667e65eeb847509797b28a.jpeg)
球在看