如何在圣人中将十进制转换为固定长度的二进制

how to convert decimal to binary with fixed length in sage

我想将十进制转换为二进制。我期待固定长度的二进制数。例如,如果固定长度为 5,则 3 转换为 00011。我需要在 sage

中处理这些

您可以编写一个小函数来执行此操作,例如:

def binary(n, length=5):
    """
    Return a binary string of specified length for this integer

    The binary string is padded with initial zeros if needed.
    The default length of 5 can be overriden.

    EXAMPLES::

        sage: binary(3)
        '00011'
        sage: binary(3, length=7)
        '0000011'
        sage: binary(3, length=1)
        ---------------------------------------------------------------------------
        ValueError                                Traceback (most recent call last)
        ...
        ValueError: Writing 3 in binary requires more than 1 bits
    """
    if length < n.nbits():
        raise ValueError('Writing {} in binary requires more than {} bits'.format(n,length))
    return '0' * (length-n.nbits()) + n.binary()

然后使用如下:

sage: binary(3)
'00011'
sage: binary(3, length=7)
'0000011'

如果你要求的长度太短,它会抛出一个 ValueError。