Am I reading this right?
There aren't 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.
Am I reading this right?
There aren't 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.
Python's string format method can take a format spec:
>>> "{0:b}".format(10)
'1010'
If you're looking for bin()
as an equivalent to hex()
, it was added in python 2.6.
No language or library will give its user base everything that they desire (although Boost may claim to :-). You should be collecting snippets of code as you develop to ensure you never have to write the same thing twice.
Such as:
def bin(i):
if i = 0:
return "0"
s = ''
while i:
if i & 1 == 1:
s = "1" + s
else:
s = "0" + s
i = i >> 1
return s
which will construct your binary string based on the decimal value.
The idea is to use code from (in order of preference):