How do I turn a python list of integers into a bytestring?
- User
How do I turn a python list of integers into a bytestring?
- Assistant
You can use the
structmodule to convert a list of integers to a bytestring. Here's an example:import struct int_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Convert the list of integers to a packed binary string byte_string = struct.pack('!10i', *int_list) print(byte_string)This will output the following bytestring:
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n'Here,
!10ispecifies that the bytestring should be packed with 10 signed integers in network byte order (big-endian). The*int_listargument unpacks the list of integers and passes them as separate arguments to thepack()function.If you want to convert the bytestring back to a list of integers, you can use the
struct.unpack()function:unpacked_list = struct.unpack('!10i', byte_string) print(list(unpacked_list))This will output the original list of integers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - User
Any other way that doesn't require the struct module?
- Assistant
Yes, you can use the
bytes()constructor along with a list comprehension to convert a list of integers to a bytestring. Here's an example:int_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Convert the list of integers to a bytestring byte_string = bytes([i.to_bytes(4, byteorder='big') for i in int_list]) print(byte_string)This will output the same bytestring as the previous example:
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n'Here, we're using a list comprehension to loop over each integer in
int_listand convert it to a 4-byte big-endian byte string using theto_bytes()method. The resulting list of byte strings is then passed to thebytes()constructor to create the final bytestring.To convert the bytestring back to a list of integers, you can use another list comprehension:
unpacked_list = [int.from_bytes(byte_string[i:i+4], byteorder='big') for i in range(0, len(byte_string), 4)] print(unpacked_list)