0

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?

user299648
  • 2,769
  • 6
  • 34
  • 43

2 Answers2

1

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

__attribute__((packed)) struct NetworkPacket {
    int integer;
    char character;
};
1

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)
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
  • The other answer has a good point, too; you can use struct packing/alignment/padding to control the layout, as well as bit width specifiers, etc. – Jesse Rusak Mar 08 '13 at 12:43