SInteger类基于位列表。它是位长度为LEN的有符号整数。LEN是在测试用例中定义的,因此您可以简单地使用它而不必重新定义它。虽然位字符串(bit_str)可能必须短于LEN,但应进行符号扩展。如果输入位字符串是空字符串,则新的SInteger对象应该是一个全零的列表。请注意,列表中存储的所有位对象都是逻辑1或0。例如,如果一个SInteger实例化如下:
位字符串为“55111140”
b=SInteger(“位串”)
b的值在处理器中存储为55555555 000050。在
我需要为SInteger实现一些方法。请注意,SInteger是一个有符号整数。它可以是负整数。为了得到一个负整数的大小,我需要进行2的补运算。在
这就是我为代码所做的,除了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')