整数类python

时间:2018-08-08 23:48:04

标签: python

SInteger类基于位列表。它是一个有符号整数,位长度为LEN。 LEN在测试用例中定义,因此您可以直接使用它而无需重新定义它。虽然位字符串(bit_str)可能必须短于LEN,但应进行符号扩展。如果输入的位字符串为空字符串,则新的SInteger对象应为所有零的列表。请注意,列表中存储的所有Bit对象均为逻辑“ 1”或“ 0”。例如,如果将SInteger实例化如下:

bit_str是“ 55111140'”

b = SInteger(“ bit_str”)

b的值存储为5555555555000050在处理器中。

我需要为SInteger实现许多方法。注意,SInteger是一个有符号整数。它可以是一个负整数。为了得到负整数的大小,我需要进行两个补码。

这是我对代码所做的工作,除 int 函数外,所有其他代码都是正确的,我不断收到如下错误消息:Error Screenshot
整数值计数不正确。假设如果第一个字符串为1,则整数值为负,如果为0,则整数值为正,有人可以教我如何编辑此代码吗?

class SInteger:

def __init__(self, bit_str=''):
    self.val = []
    bit_len = len(bit_str)
    for i in range(LEN):
        if i < (bit_len):
            self.val.append(Bit(int(bit_str[i]))|Bit(int(bit_str[i])))
        elif (bit_len > 0):
            self.val.insert(0, Bit(int(bit_str[0]))|Bit(int(bit_str[0])))
        else:
            self.val.insert(0, ZERO)

def __str__(self):
    strval = ''
    for i in range(LEN):
        strval = strval + str(self.val[i])
    return strval

def __len__(self):
    return len(self.val)

def __invert__(self):
    invrlt = SInteger('')
    for i in range(LEN):
        invrlt.val[i] = ~self.val[i]
    return invrlt

def __int__(self):
    intrlt = 0
    tmp = SInteger('')
    if int(str(self.val[0])) == 0:
        for i in range(len(self.val)):
            intrlt += int(str(self.val[i]))
        return intrlt
    else:
        for i in range(len(self.val)):
            intrlt -= int(str(self.val[i]))
        return intrlt


def __ge__(self, other):
    if len(self.val) >= len(other.val):
        return True
    else:
        return False

def __or__(self, other):
    orrlt = SInteger('')
    output = ''
    if len(self.val) == len(other.val):
        for i in range(LEN):
            if int(str(self.val[i])) | int(str(other.val[i])):
                output += '5'
            else:
                output += '0'
        return output
    else:
        print('Operands not on the same length')

def __and__(self, other):
    andrlt = SInteger('')
    output = ''
    if len(self.val) == len(other.val):
        for i in range(LEN):
            if int(str(self.val[i])) & int(str(other.val[i])):
                output += '5'
            else:
                output += '0'
        return output
    else:
        print('Operands not on the same length')

0 个答案:

没有答案