Python Forum
Pack integer values as single bytes in a struct
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pack integer values as single bytes in a struct
#1
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
Reply
#2
It seems to me that you don't need pack for this:
value_data_packed = bytes(range(128))
Reply
#3
Thank you, Gribouillis! It works!
Reply
#4
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Struct Question, decimal 10, \n and \x0a. 3python 2 648 Aug-11-2023, 09:29 AM
Last Post: 3python
  How to convert 4 bytes to an integer ? GiggsB 11 6,594 Jan-20-2022, 03:37 AM
Last Post: GiggsB
  JS Buffer.from VS struct.pack DreamingInsanity 3 2,408 Apr-05-2021, 06:27 PM
Last Post: DreamingInsanity
  struct.unpack failed Roro 2 3,278 Jun-13-2020, 05:28 PM
Last Post: DreamingInsanity
  What is the best way to return these 4 integer values? Pedroski55 4 2,491 Apr-13-2020, 09:54 PM
Last Post: Pedroski55
  struct.decode() and '\0' deanhystad 1 3,142 Apr-09-2020, 04:13 PM
Last Post: TomToad
  How does a single object see all the values inside it? jenniferruurs 1 1,796 Oct-01-2019, 04:57 PM
Last Post: stullis
  8-bit integer to bytes Garitron 1 2,948 Sep-14-2019, 11:22 PM
Last Post: ichabod801
  How to remove empty struct from matlab file in python? python_newbie09 0 2,353 Jun-25-2019, 12:13 PM
Last Post: python_newbie09
  Pack binary data to list of integers bearer 0 2,130 Mar-29-2019, 12:17 PM
Last Post: bearer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020