简体   繁体   English

如何在鼠尾草中将十进制转换为固定长度的二进制

[英]how to convert decimal to binary with fixed length in sage

I want to convert a decimal to binary. 我想将小数转换为二进制。 I am expecting binary number in the fixed length. 我期望固定长度的二进制数。 example if fixed length is 5, 3 converted as 00011. I need to work these in sage 例如,如果固定长度为5,则3转换为00011。我需要在鼠尾草中使用它们

You can write a small function to do that, like: 您可以编写一个小函数来做到这一点,例如:

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

Then use it as follows: 然后使用如下:

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

It will raise a ValueError if the length you ask is too short. 如果您要求的长度太短,则会引发ValueError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM