3

Here is a little problem: I want to create a byte stream (a table of byte integer) from different data type, integer of variable length, string.

val1 = 0x2
val2 = 0x0001020304050607
val3 = "blablabla"

And I want to obtain a stream like:

byteStream = val1 + val2 + val3
byteStream = [0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x62, 0x6c, 0x61, 0x62, 0x6c, 0x61, 0x62, 0x6c, 0x61]

I have tried several things, like using a intermediate string and then convert this in byte. But this solution is ugly, and does not work properly.

Any help welcomed. Thanks.

1 Answer 1

3
import struct

val1 = 0x2
val2 = 0x0001020304050607
val3 = "blablabla"

data=struct.pack('>BQ9s',val1,val2,val3)
print repr(data)

yields

'\x02\x00\x01\x02\x03\x04\x05\x06\x07blablabla'

BQ9s tells struct.pack to pack one unsigned int (1 byte) , followed by one unsigned long long (8 bytes) followed by 9 chars (1 byte each). The list of possible format characters can be found here.

data is a string (that is, a sequence of bytes). If you wish to ultimately have a list, you could use list(data).

Sign up to request clarification or add additional context in comments.

2 Comments

where are methods to_bytes and from_bytes I did not found on the dic
@Xavier Combelle: to_bytes is new ... introduced in Python 3.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.