python struct pack with space padding
Asked Answered
U

2

5

I need to create/send binary data in python using a given protocol. The protocol calls for fixed width fields , with space padding thrown in. Using python's struct.pack, the only thing I can think of is, calculating the space padding and adding it in myself. Is there a better way to achieve this?

thanks

Undersheriff answered 26/10, 2012 at 15:12 Comment(1)
space padding as in the space character or space padding as in padding with 0 bytes?America
A
8

struct has a placeholder (x) for a padding byte you can use:

 # pack 2 16 bit values plus one pad byte
 from struct import pack
 packedStrWithOneBytePad = pack("hhx", 1000, 2000)
America answered 26/10, 2012 at 15:16 Comment(4)
Nothing in the documentation indicates, that you can specify what the pad should be.. and I think I read that it is by default null. Though I can't seem to find it now.Undersheriff
@Undersheriff yeah I doubt you can configure the pad. You might just need to fill the pad yourself with a normal byte and specify what character you want to use.America
Ok. thanks. Just wanted to make sure , that was the only way.Undersheriff
This answer doesn't answer the question, at all.Mercator
M
1

For a 64bit based CPU, use '0l' to align the bytes with a repeat count of zero.

Example:
bytes = struct.pack('???0l',1,2,3)
print(len(bytes)) // will print 8

Manners answered 9/6, 2022 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.