python类整数_整数类python

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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值