将二进制字符串转换为二进制补码

时间:2016-03-28 23:13:31

标签: 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):
        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。除了基础知识之外,我们无法真正使用任何花哨的字符串格式,内置函数等。

1 个答案:

答案 0 :(得分:0)

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

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