Python Forum
Pack integer values as single bytes in a struct - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Pack integer values as single bytes in a struct (/thread-27439.html)



Pack integer values as single bytes in a struct - bhdschmidt - Jun-07-2020

Hello,

I try to put 128 values into a struct to write this data of the struct to a file. This is my code:

import struct

values = []
for value in range(0, 128):
    values.append(value)

value_data = [chr(value) for value in values]

value_obj = struct.Struct('%dc' % 128)

value_data_packed = value_obj.pack(*value_data)

f = open('test.bin', "wb")
f.write(value_data_packed)
f.close()
I always received the struct.error: char format requires a bytes object of length 1

I tried different code snippets from the web, but none did work. Can you help me?

Thank you in advance,
Bernhard


RE: Pack integer values as single bytes in a struct - Gribouillis - Jun-07-2020

It seems to me that you don't need pack for this:
value_data_packed = bytes(range(128))



RE: Pack integer values as single bytes in a struct - bhdschmidt - Jun-07-2020

Thank you, Gribouillis! It works!


RE: Pack integer values as single bytes in a struct - bhdschmidt - Jun-09-2020

I found the mistake in my code; now it works with the struct pack function:

import struct

values = []
for value in range(0, 128):
    values.append(value)

value_obj = struct.Struct('%dB' % 128)

value_data_packed = value_obj.pack(*values)

f = open('test.bin', "wb")
f.write(value_data_packed)
f.close()