Peter
Peter

Reputation: 2414

Python struct string to bin

I´m learning Python. Seeing the module struct, I found a doubt:

Is it possible to convert a "string" to "bin" without giving the length.

For the case (with chars length)

F = open("data.bin", "wb")

import struct
data = struct.pack("24s",b"This is an unknown string")
print(data)

F.write(data)

F.close()

I´m trying to do the same but with unknown length. Thanks a lot!

Upvotes: 0

Views: 2659

Answers (3)

Peter
Peter

Reputation: 2414

Thanks to both... My new code:

F = open("data.bin", "wb")

strs = b"This is an unkown string"

import struct
data = struct.pack("{0}s".format(len(strs)),strs)
print(data)

F.write(data)

F.close()

Upvotes: 1

horns
horns

Reputation: 1933

If you have the string, use len to determine the length of the string.

i.e

data = struct.pack("{0}s".format(len(unknown_string)), unknown_string)

Upvotes: 1

shuttle87
shuttle87

Reputation: 15954

The Bytes type is a binary data type, it just stores a bunch of 8bit characters. Note that the code with struct.pack ends up creating a bytes object:

>>> import struct
>>> data = struct.pack("24s",b"This is an unknown string")
>>> type(data)
<class 'bytes'>
>>> len(data)
24

The length of this is 24 as per your format specifier. If you just want to place the bytes-string directly into the file without doing any length checking you don't even need to use the struct module, you can just write it directly to the file:

F = open("data.bin", "wb")
F.write(b"This will work")

If however you wanted to keep the 24 bytes length you could keep using struct.pack:

>>> data = struct.pack("24s",b"This is an unknown st")
>>> len(data)
24
>>> print(data)
b'This is an unknown st\x00\x00\x00'
>>> data = struct.pack("24s",b"This is an unknown string abcdef")
>>> print(data)
b'This is an unknown strin'

In the case of supplying a bytes that is too short struct.pack pads the remainder with 0's and in the case where it's too long it truncates it.

If you don't mind getting the missing space padded out with zeros you can just pass in the bytes object directly to struct.pack and it will handle it.

Upvotes: 1

Related Questions