c++将十进制转换为二进制 小数_每日一课 | Python将int转换为二进制字符串

064773784d2f59f04e3684da04a14c52.png

在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)

参考文献:

  1. Python bin文件
  2. Python格式文件
  3. Python格式规范迷你语言
翻译自: https://mkyong.com/python/python-how-to-convert-int-to-a-binary-string/ 推荐阅读-- 每周一课 | Python 示例拆分字符串入到字典里面

每日一课 | 如何将String转换为int

每日一课 | Python time.sleep 精准延迟到秒

每日一课 | Python 如何判断一个字符串是否包含另一个字符串?

640?wx_fmt=svg

球分享

640?wx_fmt=svg

球点赞

4bb740d437f0300dc7e904cf3176f56d.png

球在看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值