【问题标题】:Python - Incrementing a binary sequence while maintaining the bit lengthPython - 在保持位长的同时增加二进制序列
【发布时间】:2013-05-01 10:39:24
【问题描述】:

我试图在 python 中增加二进制序列,同时保持位长。 到目前为止,我正在使用这段代码...

'{0:b}'.format(long('0100', 2) + 1)

这将获取二进制数,将其转换为长整数,加一,然后将其转换回二进制数。例如,01 -> 10。

但是,如果我输入一个数字,例如“0100”,而不是将其增加到“0101”,我的代码 将其增加到“101”,因此它忽略第一个“0”,而只是增加“100” 到“101”。

任何有关如何使我的代码保持位长的帮助将不胜感激。 谢谢

【问题讨论】:

    标签: python binary


    【解决方案1】:

    str.format 允许您将长度指定为这样的参数

    >>> n = '0100'
    >>> '{:0{}b}'.format(long(n, 2) + 1, len(n))
    '0101'
    

    【讨论】:

    • 非常感谢,这正是我想要的!
    【解决方案2】:

    这是因为 5 在从 int(或 long)转换为二进制后表示为“101”,因此在它之前添加一些 0 前缀,您可以使用 0 作为填充符并传递初始二进制数的宽度格式化时。

    In [35]: b='0100'
    
    In [36]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
    Out[36]: '0101'
    
    In [37]: b='0010000'
    
    In [38]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
    Out[38]: '0010001'
    

    【讨论】:

    • 这在这种情况下不起作用'{0:04b}'.format(long('0000010100', 2) + 1),因为您将宽度固定为 4,而不是按照 OP 的要求使用输入的长度。 (当然,考虑到你所拥有的,也许 OP 应该弄清楚......) :)
    • @RayToal 我正要补充。
    【解决方案3】:

    这可能最好使用format strings 解决。获取输入的长度,从中构造一个格式字符串,然后用它来打印递增的数字。

    from __future__ import print_function
    # Input here, as a string
    s = "0101"
    # Convert to a number
    n = long(s, 2)
    # Construct a format string
    f = "0{}b".format(len(s))
    # Format the incremented number; this is your output
    t = format(n + 1, f)
    print(t)
    

    要硬编码到四个二进制位(左填充 0),您将使用 04b,五个您将使用 05b,等等。在上面的代码中,我们只获取输入字符串的长度。

    哦,如果您输入像1111 这样的数字并加1,您将得到10000,因为您需要一个额外的位来表示它。如果您想转至0000,请执行t = format(n + 1, f)[-len(s):]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-06
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多