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.
To convert int to binary in Python, use the bin() method. The bin() is a built-in Python method that converts a decimal to a binary data type. The bin() function accepts a number as an argument and returns its equivalent binary string prefixed with “0b”.
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With