REDrodder
REDrodder

Reputation: 3

how to take n-bytes from byte string and convert them to one integer

I have long byte string like b'\x00\x95\xf3\x4c ...'. I want read from this string by n bytes and convert them as if they are one integer

I have tried slices

list_of_int = []
data = b'' #it`s big byte string

while len(data) > 0:
        list_of_int.append(int.from_bytes(data[:4], 'big'))
        data = data[4:]

but them are too slow, how can I do it faster?

Upvotes: 0

Views: 66

Answers (1)

Jav
Jav

Reputation: 1607

You can use struct.

If the number of items is known (n), you can unpack all items at once with unpack("i"*n, data). Else, as suggested by juanpa-arrivillaga, you should iteratively unpack with iter_unpack("i", data).

import struct

# Building a list of integers
l = [1, 242, 2430, 100, 20]

# Converting it to bytes string
data = bytearray()
for i in l:
    data += i.to_bytes(4, 'little')  # using 'little-endian' representation
print(data)

# Reading bytes string
n = len(l)
list_of_int = struct.unpack("i"*n, data) # reads n integers. Use ">i"*8 for big-endian representation
print(list_of_int)

Upvotes: 1

Related Questions