Python中如何將整數轉換為二進制字符串


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)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM