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


Messages In This Thread
Pack integer values as single bytes in a struct - by bhdschmidt - Jun-07-2020, 06:16 AM

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