oneb1got
oneb1got

Reputation: 153

How do I serialize a struct of 8bit integers for socket programming?

I have a struct that has 5 unsigned 8 bit integers that mimics a frame with 5 packets. After researching, I know need to serialize the data, field by field, especially since I am sending from a Windows machine to a Linux machine and back.

here is my struct:

typedef struct pressure{
    UINT8       a;
    UINT8       b;
    UINT8       c;
    UINT8       d;
    UINT8       e;
}pressure;

The issue is I cant use htons() since my members must be 8 bits. How do I manually serialize this? It would be greatly appreciated if you could provide a short code sample that shows how to serialize and what to pass to send().

Upvotes: 0

Views: 177

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106226

You can either write each individual byte using ostream::put, or - if you've ensured they're contiguous in memory in pressure (which will be done on every compiler I've ever used without you doing anything actively) - write the lot of them using ostream::write, as in:

my_ostream.write(static_cast<const char*>(&my_pressure.a), 5);

That said, consider keeping the values in an array so you're guaranteed they're contiguous in memory.

You don't need htonX / ntohX etc. - they're for normalising/denormalising multi-byte integer representations, which you don't have here.

Upvotes: 3

James Anderson
James Anderson

Reputation: 27478

Just write it if you are sending from an Intel x86 based machine to another Intel x86 machine (which most linuxes are).

If however you plan to send it to a machine based on another processor the safest thing is to just send ASCI characters so something like:

 char[] buffer = sprintf("|%03d|%03d|%03d|%03d|%03d|",a,b,c,d,e);

Would give you a fixed length string readable by any machine. Its a good idea to have some sort of field separator (the "|" in this case) to help the receiver verify the string has not been garbled by an unreliable network.

Upvotes: 0

Related Questions