将字符串解析为整数时出错

时间:2016-09-17 18:17:29

标签: python parsing

我有这两个,似乎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

1 个答案:

答案 0 :(得分:0)

字节被错误地反转,然后它将符号位解析为数字。修复了两个错误。

def onebit2integer(b):
    if b in (b"0", b"\x00"):
        return 0
    if b in (b"1", b"\x01"):
        return 1
    raise ValueError(r"bit was not recognized as one of: 0 1 \x00 \x01")


def bits2integer(data, signed=False):
    number = 0
    for b in iteratebytes(data):
        number = (number << 1) | onebit2integer(b)

    if signed and onebit2integer(data[0:1]):
        bias = 1 << (len(data) -1)
        return number - bias*2
    else:
        return number


def bytes2integer(data, signed=False):
    number = 0
    for b in iterateints(data):
        number = (number << 8) | b

    if signed and byte2int(bytes2bits(data[0:1])[0:1]):
        bias = 1 << (len(data)*8 -1)
        return number - bias*2
    else:
        return number