Python int to binary string?

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

提交回复
热议问题