【问题标题】:Convert binary string into two's complement将二进制字符串转换为二进制补码
【发布时间】:2016-07-16 07:51:49
【问题描述】:

对于我们的家庭作业,我们被要求输入一个整数并返回它的二进制补码。

目前,我能够将整数转换为二进制字符串。从那里,我知道我需要反转 0 和 1 并将 1 添加到新字符串中,但我不知道该怎么做。

有人可以帮我解决这个问题吗?

def numToBinary(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    result = ''  
    for x in range(8):
        r = n % 2 
        n = n // 2
        result += str(r)

    result = result[::-1]
    return result

def NumToTc(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    binary = numToBinary(n)
    # stops working here
    invert = binary
    i = 0
    for digit in range(len(binary)):
        if digit == '0':
            invert[i] = '1'
        else:
            invert[i] = '0'
        i += 1
    return invert

注意:这是入门级课程,所以我们主要坚持使用loopsrecursion。除了基础之外,我们不能真正使用任何花哨的字符串格式、内置函数等。

【问题讨论】:

  • 既然是作业——我觉得只能给个提示。在 PHP 手册中查找您的二进制操作。使用在线手册。其中一位会告诉你如何做到这一点。
  • 冒着放弃分配的风险,请注意 Python 定义了一些非常有用的 bitwise operators...
  • 让我猜猜,你有TypeError: 'str' object does not support item assignment,不是吗?请附上您在发布问题时收到的错误消息,这样可以大大更轻松地帮助您解决实际问题。
  • @Liongold 谢谢你的链接。我能够解决它。
  • @MarkManning 感谢您的洞察力。我能弄明白。

标签: python binary twos-complement


【解决方案1】:

通过执行以下操作,我能够找到我的解决方案:

def numToBinary(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    result = ''  
    for x in range(8):
        r = n % 2 
        n = n // 2
        result += str(r)

    result = result[::-1]
    return result

def NumToTc(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    binary = numToBinary(n)
    for digit in binary:
        if int(digit) < 0:
            binary = (1 << 8) + n
    return binary

【讨论】:

  • @Liongold 我不太确定我是否跟随。如果您不介意,可以给我举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2021-02-24
  • 2015-04-19
  • 2013-09-28
  • 2016-08-31
  • 1970-01-01
  • 2014-03-01
相关资源
最近更新 更多