如何在sage中将十进制转换为具有固定长度的二进制

时间:2016-02-29 05:00:43

标签: python sage

我想将小数转换为二进制。我期待固定长度的二进制数。例如,如果固定长度是5,3则转换为00011.我需要在sage中使用它们

1 个答案:

答案 0 :(得分:0)

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

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。