discort
discort

Reputation: 728

Unable convert to int from bytes

I have the next value

value = bytearray(b'\x85\x13\xbd|\xfb\xbc\xc3\x95\xbeL6L\xfa\xbf0U_`$]\xca\xee]z\xef\xa0\xd6(\x15\x8b\xca\x0e\x1f7\xa9\xf0\xa4\x98\xc5\xdf\xcdM5\xef\xc2\x052`\xeb\x13\xd9\x99B.\x95\xb2\xbd\x96\xd9\x14\xe6F\x9e\xfd\xd8\x00')

when I try to convert in python3.x it works well.

>>> int.from_bytes(value, byteorder='little')
2909369579440607969688280064437289348250138784421305732473112318543540722321676649649580720015118044118243611774710427666475769804427735898727217762490192773

How to convert it in python2.7? I already read the convert a string of bytes into an int (python)

struct.unpack(fmt, value)[0]

But don't know what to do with fmt.

Upvotes: 3

Views: 6622

Answers (2)

Robᵩ
Robᵩ

Reputation: 168616

You can use a combination of .encode('hex') and int(x, 16):

num = int(str(value).encode('hex'), 16)

Note that you need to use something like

int(''.join(reversed(value)).encode('hex'), 16)

in order to parse it as little endian.

reference: https://stackoverflow.com/a/444814/8747

Upvotes: 4

poke
poke

Reputation: 387547

You can just write your own from_bytes function in Python 2:

def from_bytes (data, big_endian = False):
    if isinstance(data, str):
        data = bytearray(data)
    if big_endian:
        data = reversed(data)
    num = 0
    for offset, byte in enumerate(data):
        num += byte << (offset * 8)
    return num

Used like this:

>>> data = b'\x85\x13\xbd|\xfb\xbc\xc3\x95\xbeL6L\xfa\xbf0U_`$]\xca\xee]z\xef\xa0\xd6(\x15\x8b\xca\x0e\x1f7\xa9\xf0\xa4\x98\xc5\xdf\xcdM5\xef\xc2\x052`\xeb\x13\xd9\x99B.\x95\xb2\xbd\x96\xd9\x14\xe6F\x9e\xfd\xd8\x00'
>>> from_bytes(data)
2909369579440607969688280064437289348250138784421305732473112318543540722321676649649580720015118044118243611774710427666475769804427735898727217762490192773L

As for struct, you cannot really use this, as it only supports unpacking elements of a certain kind, up to 8 byte integers. But since you want to handle arbitrary byte strings, you will have to use something else.

Upvotes: 6

Related Questions