tags:

views:

348

answers:

4

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.

+1  A: 

Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is struct

Van Gale
+6  A: 

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

>>> "{0:b}".format(10)
'1010'
Tung Nguyen
str.format() is new in version 2.6: http://docs.python.org/library/stdtypes.html
Mark Roddy
+6  A: 

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

John Fouhy
+5  A: 

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):

  • the language.
  • the libraries.
  • third-party libraries with suitable licenses.
  • your own collection.
  • something new you need to write (and save in your collection for later).
paxdiablo