Python Forum

Full Version: Pack integer values as single bytes in a struct
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
It seems to me that you don't need pack for this:
value_data_packed = bytes(range(128))
Thank you, Gribouillis! It works!
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()