Python - 对字符串应用补码
我正在尝试将二进制补码添加到用字符串表示的二进制数中。 假设字符串已经被翻转,我将如何“添加”1到最后一个字符,并根据需要替换字符串中的其他字符?
示例:100010 翻转为 011101,并表示为字符串。如何将补码应用于 011101 字符串?
其中真正让我困惑的部分是,如果用户输入一个二进制数,那么在应用二进制补码时,会涉及大量进位。
I am trying to add the Two's Complement to a Binary number represented with a string.
Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed?
Example: 100010 is flipped to 011101, and is represented as a string. How would you apply the Two's Complement to the 011101 string?
One part of this that really has me puzzled is if the user enters a binary number that, when the two's complement is applied, involves a lot of carrying.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只是将其作为数字,然后将其转换回来。
I'd just do it as a number, then convert it back.
为了多样化,这里还有另一种方法,基于“补码”被定义为“补码”加一这一事实。这有点作弊,将中间的补码字符串值转换为整数并加一,然后使用
bin()
中添加的新内置函数将其转换回二进制字符串Python 2.6。Just for variety, here's yet another way based on the fact the Two's Complement is defined as the One's Complement plus one. This cheats a little and converts the intermediate one's complement string value into an integer to add one to it, and then converts it back to a binary string using the new built-in
bin()
function added in Python 2.6.如果您想在不转换回数字的情况下执行此操作,请从字符串右侧开始,直到找到第一个 1,然后将所有字符翻转到其左侧。
if you want to do it without converting back to a number, start from the right of the string until you find the first 1, then flip all chars to its left.