Main Tutorials

Python – How to convert int to a binary string?

In Python, we can use bin() or format() to convert an integer into a binary string representation.


  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)

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
miguel
2 years ago

# word6: 3F3C4109 00 1111110011110001 00000100 001001
# mot 7 : 95AAE46F 10 010101101010101110010001 101111

I want make binary with the 2 string in bold 00000100010101101010101110010001
and multoply by math.pow(2,-33)
When I do manualy with caractere 0b, it is Ok, but not in programme

s= Ob00000100010101101010101110010001

v= s * math.pow(2,-33

My question is how convert string to binary ?

Koki Kurene
2 years ago

how do i convert any numbers to binary not just 10 and 1.

Mostafa Touny
3 years ago

Thank you. That was really helpful