Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将二进制字符串转换为两个';补语_Python_Binary_Twos Complement - Fatal编程技术网

Python 将二进制字符串转换为两个';补语

Python 将二进制字符串转换为两个';补语,python,binary,twos-complement,Python,Binary,Twos Complement,对于我们的家庭作业,我们被要求输入一个整数,并返回二者的补数 目前,我能够将整数转换为二进制字符串。从那里,我知道我需要反转0和1,并将1添加到新字符串中,但我不知道如何做到这一点 有人能帮我吗 def numToBinary(n): '''Returns the string with the binary representation of non-negative integer n.''' result = '' for x in range(8):

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

目前,我能够将整数转换为二进制字符串。从那里,我知道我需要反转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

注意:这是一门入门级课程,因此我们主要坚持使用
循环
递归
。除了基本功能外,我们无法真正使用任何别致的字符串格式、内置函数等。

我通过以下操作实现了我的解决方案:

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
def NUMTOBINAL(n):
''返回二进制表示为非负整数n的字符串。''
结果=“”
对于范围(8)内的x:
r=n%2
n=n//2
结果+=str(r)
结果=结果[:-1]
返回结果
def NumToTc(n):
''返回二进制表示为非负整数n的字符串。''
二进制=num二进制(n)
对于二进制数字:
如果int(数字)<0:

二进制=(1)由于这是一个赋值-我觉得我只能给出一个提示。请在PHP手册中查找您的二进制操作。使用在线手册。其中一个将告诉您如何执行此操作。冒着放弃赋值的风险,请注意Python定义了一些非常有用的函数……让我猜一下,您得到了一个
TypeError:'str'对象不支持项assig是吗?
请将发帖时收到的错误信息包括在内,这样可以更轻松地帮助您解决实际问题。@Liongold感谢您提供的链接。我能够解决它。@MarkManning感谢您提供的见解。我能够解决它。@Liongold我不太确定我是否理解。您能给我一个e吗例如,如果你不介意的话?