2016-09-17 165 views
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 

回答

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