Python int to binary string?

Python int to binary string?

Pythons 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 youre looking for bin() as an equivalent to hex(), it was added in python 2.6.

Example:

>>> bin(10)
0b1010

Python int to binary string?

Python actually does have something already built in for this, the ability to do operations such as {0:b}.format(42), which will give you the bit pattern (in a string) for 42, or 101010.


For a more general philosophy, no language or library will give its user base everything that they desire. If youre working in an environment that doesnt provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example, the pseudo-code:

define intToBinString, receiving intVal:
    if intVal is equal to zero:
        return 0
    set strVal to 
    while intVal is greater than zero:
        if intVal is odd:
            prefix 1 to strVal
        else:
            prefix 0 to strVal
        divide intVal by two, rounding down
    return strVal

which will construct your binary string based on the decimal value. Just keep in mind thats a generic bit of pseudo-code which may not be the most efficient way of doing it though, with the iterations you seem to be proposing, it wont make much difference. Its really just meant as a guideline on how it could be done.

The general idea is to use code from (in order of preference):

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

Leave a Reply

Your email address will not be published. Required fields are marked *