Jinoh  Kim
Jinoh Kim

Reputation: 45

Convert C data type to Python

I want to bind multiple size of data such as one byte value, two byte value, one byte value and then string. This is a packet to be sent by a simple chatting client.

The network packet I want to make is in the diagram. Total 4 bytes header followed by body. enter image description here

How can I make this packet by Python??

Is there any solution for storing data with explicit definition of size?

Upvotes: 2

Views: 685

Answers (1)

Tim Sweet
Tim Sweet

Reputation: 645

You're looking for Python's struct. Here's an example of how to do what you're asking with struct:

from struct import *
header = pack('!chcs', clientID, bodySize, networkMessageId, body)

Now header will have that packet in it, and you can send it over the network (or whatever you need to do with it).

Since your image says "network" I assume this needs to be in network byte order, that's what the ! at the beginning means.

Upvotes: 4

Related Questions