Question

Coming from python I could do something like this.

values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packet = s.pack(*values)

I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C?

Was it helpful?

Solution

Using a C struct is the normal approach. For example:

typedef struct {
    int a;
    char foo[2];
    float b;
} MyPacket;

Would define a type for an int, 2 characters and a float. You can then interpret those bytes as a byte array for writing:

MyPacket p = {.a = 2, .b = 2.7};
p.foo[0] = 'a'; 
p.foo[1] = 'b';

char *toWrite = (char *)&p; // a buffer of size sizeof(p)

OTHER TIPS

Not very clear a question, but maybe you're looking for a (packed struct)?

__attribute__((packed)) struct NetworkPacket {
    int integer;
    char character;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top