Python - 将二进制补码应用于字符串

标签 python twos-complement

我正在尝试将二进制补码添加到用字符串表示的二进制数中。 假设字符串已经翻转,我将如何向最后一个字符“添加”1,并根据需要替换字符串中的其他字符?

示例:100010 翻转为 011101,并表示为字符串。如何将二进制补码应用于 011101 字符串?

其中真正让我感到困惑的部分是,如果用户输入一个二进制数,那么当应用二进制补码时,会涉及很多进位。

最佳答案

我只是把它作为一个数字,然后将它转换回来。

def tobin(x, count=8):
    # robbed from http://code.activestate.com/recipes/219300/
    return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))

def twoscomp(num_str):
    return tobin(-int(num_str,2),len(num_str))

print twoscomp('01001001') # prints 10110111
print twoscomp('1000')     # prints 1000 (because two's comp is cool like that)
print twoscomp('001')      # prints 111

关于Python - 将二进制补码应用于字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3920873/

相关文章:

python - 将列数据值的计数累积为单独的列

java - 如何定义嵌套类常量?

python - 如何在新行字符上拆分 Python 字符串

c - Unsigned/Signed Arthmetic Problems from A Programmer's Perspective 教科书

assembly - ARM中如何获取寄存器值的二进制补码?

c++ - 为什么 long long 2147483647 + 1 = -2147483648?

python - 按第一个元素值对数组进行分组 Python

python - 正则表达式 anchor \< 与\b 用于字边界

c - C 中的二进制加法,来自数组

c - (C 语言) 有没有办法在 while 循环中放置两个不同的可能整数值的条件参数?