Python int to binary string?

后端 未结 30 1676
执念已碎
执念已碎 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:44

    To calculate binary of numbers:

    print("Binary is {0:>08b}".format(16))
    

    To calculate the Hexa decimal of a number:

    print("Hexa Decimal is {0:>0x}".format(15))
    

    To Calculate all the binary no till 16::

    for i in range(17):
       print("{0:>2}: binary is {0:>08b}".format(i))
    

    To calculate Hexa decimal no till 17

     for i in range(17):
        print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
    ##as 2 digit is enogh for hexa decimal representation of a number
    
    0 讨论(0)
  • 2020-11-22 05:46

    Summary of alternatives:

    n=42
    assert  "-101010" == format(-n, 'b')
    assert  "-101010" == "{0:b}".format(-n)
    assert  "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
    assert "0b101010" == bin(n)
    assert   "101010" == bin(n)[2:]   # But this won't work for negative numbers.
    

    Contributors include John Fouhy, Tung Nguyen, mVChr, Martin Thoma. and Martijn Pieters.

    0 讨论(0)
  • 2020-11-22 05:46

    I am surprised there is no mention of a nice way to accomplish this using formatting strings. TLDR:

    >>> number = 1
    >>> f'0b{number:08b}'
    '0b00000001'
    

    Longer story

    This is functionality of formatting strings:

    >>> x, y, z = 1, 2, 3
    >>> f'{x} {y} {2*z}'
    '1 2 6'
    

    You can request binary as well:

    >>> f'{z:b}'
    '11'
    

    Specify the width:

    >>> f'{z:8b}'
    '      11'
    

    Request zero padding:

    f'{z:08b}'
    '00000011'
    

    And add common suffix for binary:

    >>> f'0b{z:08b}'
    '0b00000011'
    
    0 讨论(0)
  • 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).
    0 讨论(0)
  • 2020-11-22 05:51
    try:
        while True:
            p = ""
            a = input()
            while a != 0:
                l = a % 2
                b = a - l
                a = b / 2
                p = str(l) + p
            print(p)
    except:
        print ("write 1 number")
    
    0 讨论(0)
  • 2020-11-22 05:53

    A simple way to do that is to use string format, see this page.

    >> "{0:b}".format(10)
    '1010'
    

    And if you want to have a fixed length of the binary string, you can use this:

    >> "{0:{fill}8b}".format(10, fill='0')
    '00001010'
    

    If two's complement is required, then the following line can be used:

    '{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)
    

    where n is the width of the binary string.

    0 讨论(0)
提交回复
热议问题