2
我有這兩個,似乎bytes2integer是錯誤的,但我消除了所有其他問題。哪裏不對? p3compat提供了一些幫助功能。另外,-int(data[1:], 2)
也不起作用,但這不是正確的必要條件。代碼是PY2和PY3。錯誤的解析字符串整數
def bits2integer(data, signed=False):
data = "".join("01"[b & 1] for b in iterateints(data))
if signed and data[0] == "1":
# return -int(data[1:], 2)
data = data[1:]
bias = 1 << len(data)
return int(data, 2) - bias
else:
return int(data, 2)
def bytes2integer(data, signed=False):
number = 0
for b in iterateints(data[::-1]):
number = (number << 8) | b
if signed and byte2int(bytes2bits(data[0:1])[0:1]):
# data = data[1:]
bias = 1 << (len(data)*8 -1)
return number - bias
else:
return number
Tests返回這些錯誤:
returned 6124614018247163903, expected -300
returned -9079256848778919937, expected -255
returned 2089670227099910143, expected -100
returned 9223372036854775807, expected -1
returned 72057594037927936, expected 1
returned 7205759403792793600, expected 100
returned 18374686479671623680, expected 255
returned 3170815612645539840, expected 300