Python int to binary string?


Question

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.

1
446
4/30/2019 10:06:54 AM

Accepted Answer

Python's string format method can take a format spec.

>>> "{0:b}".format(37)
'100101'

Format spec docs for Python 2

Format spec docs for Python 3

630
10/31/2017 12:19:23 PM

If you're looking for bin() as an equivalent to hex(), it was added in python 2.6.

Example:

>>> bin(10)
'0b1010'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon