Python int to binary string? Python int to binary string? python python

Python int to binary 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're looking for bin() as an equivalent to hex(), it was added in python 2.6.


>>> bin(10)'0b1010'

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 you're working in an environment that doesn't 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 that's 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 won't make much difference. It's 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).