Error in parsing strings to ints
<p>I have these two and it seems that bytes2integer is wrong, but I eliminated all the other issues. What is wrong? <a href="https://github.com/construct/construct/blob/master/construct/lib/py3compat.py" rel="nofollow">p3compat</a> provides some helper functions. On side note, <code>-int(data[1:], 2)</code> also doesnt work but that isnt necessary for correctness. Code is both PY2 and PY3.</p>

<pre><code>def bits2integer(data, signed=False):
    data = "".join("01"[b &amp; 1] for b in iterateints(data))
    if signed and data[0] == "1":
        # return -int(data[1:], 2)
        data = data[1:]
        bias = 1 &lt;&lt; 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 &lt;&lt; 8) | b

    if signed and byte2int(bytes2bits(data[0:1])[0:1]):
        # data = data[1:]
        bias = 1 &lt;&lt; (len(data)*8 -1)
        return number - bias
    else:
        return number
</code></pre>

<p><a href="https://github.com/construct/construct/blob/add-binary/tests/test_lib.py#L33" rel="nofollow">Tests</a> returned these errors:</p>

<pre><code>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
</code></pre>

<p>Bytes were reversed wrongly, and then it parsed the sign bit into number. Two bugs fixed.</p>

<pre><code>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 &lt;&lt; 1) | onebit2integer(b)

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


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

    if signed and byte2int(bytes2bits(data[0:1])[0:1]):
        bias = 1 &lt;&lt; (len(data)*8 -1)
        return number - bias*2
    else:
        return number
</code></pre>

python parsing