In searching how to do conversions recently, I found some nice code for this, using bit shifting:
n = 9
b = ''
while n > 0:
b = str(n % 2) + b
n >>= 1
print(b) # 1001
But then I learned there is now a built-in bin function included in 2.6:
>>> bin(9) 0b1001
Or you might try something like:
>>> bin(9)[2:].zfill(8) 00001001
Previous to 2.6, you could already convert binary to decimal with the int function:
>>> int('1001', 2) # second parameter is the base
9
And now in 2.6, the binary literal (0b) removes the need for a function at all:
>>> b = 0b1001 >>> b 9
I was interested to find Guido Van Rossum’s comment opposed to a bin function, from a 2006 posting:
This has been brought up many times before. The value of bin() is really rather minimal except when you’re just learning about binary numbers; and then writing it yourself is a useful exercise.
I’m not saying that bin() is useless — but IMO its (small) value doesn’t warrant making, maintaining and documenting a new built-in function.
–Guido
Which is sensible, but I still like having the bin function and I’m glad they added it anyway.
