我正在尝试将二进制补码添加到用字符串表示的二进制数中。 假设字符串已经翻转,我将如何向最后一个字符“添加”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/