Python int to binary string?

后端 未结 30 1631
执念已碎
执念已碎 2020-11-22 05:34

Are there 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

30条回答
  •  盖世英雄少女心
    2020-11-22 05:51

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

提交回复
热议问题