Simplify data packet assemble in C Below code just for assemble data into network packet. but the code logic has many repeat parts to convert integer for byte array. what's the best method for such purpose to simplify below logic?

typedef struct _INFO {
    int pid;
    int score;
} INFO;

void send_packet(int connfd,INFO* info,int len) {
    int buflen = len*8 + 8;
    unsigned char* buf = (int*)malloc(buflen);
    int p = 0;
    buf[p++] = 0x55;
    buf[p++] = 0x55;
    buf[p++] = 0x55;
    buf[p++] = 0x55;

    buf[p++] = buflen &amp; 0xFF;
    buf[p++] = (buflen &gt;&gt; 8) &amp; 0xFF;
    buf[p++] = (buflen &gt;&gt; 16) &amp; 0xFF;
    buf[p++] = (buflen &gt;&gt; 24) &amp; 0xFF;
    for (int i=0;i&lt;len;i++) {
        buf[p++] = info[i].pid &amp; 0xFF;
        buf[p++] = (info[i].pid &gt;&gt; 8) &amp; 0xFF;
        buf[p++] = (info[i].pid &gt;&gt; 16) &amp; 0xFF;
        buf[p++] = (info[i].pid &gt;&gt; 24) &amp; 0xFF;

        buf[p++] = info[i].score &amp; 0xFF;
        buf[p++] = (info[i].score &gt;&gt; 8) &amp; 0xFF;
        buf[p++] = (info[i].score &gt;&gt; 16) &amp; 0xFF;
        buf[p++] = (info[i].score &gt;&gt; 24) &amp; 0xFF;
    }
    write(connfd, buf, buflen);
    free(buf);
}
what's the best method for such purpose to simplify below logic?


With a helper function as there is  repetitive code.

#include &lt;stdint.h&gt;

// Write 32-bit integer in little endian order to buf
unsigned char *u32tobuf(unsigned char *buf, uint32_t value) {
  buf[0] = value;
  buf[1] = value &gt;&gt; 8;
  buf[2] = value &gt;&gt; 16;
  buf[3] = value &gt;&gt; 24;
  return buf + 4;
}


I'd also 1) add some error checking, 2) drop the unneeded cast 3) prevent int overflow 4) use const.

// Return error status
int send_packet(int connfd, const INFO* info, int len) {
    uint32_t buflen = len*8lu + 8;
    unsigned char* buf = malloc(buflen);
    if (buf == NULL) {
      return 1; // or perhaps some enum
    }
    unsigned char* p = u32tobuf(buf, 0x55555555);
    p = u32tobuf(p, buflen);
    for (int i=0; i&lt;len; i++) {
      p = u32tobuf(p, info[i].pid);
      p = u32tobuf(p, info[i].score);
    }
    ssize_t write_count = write(connfd, buf, buflen);
    free(buf);
    if (write_count != buflen) [
      return 1; // or perhaps some enum
    }
    return 0;
}