networking · intermediate · ~15 min

htons via bytes

Serialise a 16-bit value to network order.

Challenge

Serialise a 16-bit value to network (big-endian) byte order by writing the bytes yourself — no htons needed, so it works on any host.

Task

Implement void htons_bytes(unsigned short x, unsigned char *out) that writes x as two big-endian bytes: out[0] is the high byte, out[1] the low byte.

Input

  • x: a 16-bit value.
  • out: a 2-byte buffer to write into.

Output

None (void). After the call, out[0] = high byte of x, out[1] = low byte of x.

Example

htons_bytes(0x1234, out)  ->  out = {0x12, 0x34}
htons_bytes(80, out)      ->  out = {0x00, 0x50}

Input format

x: a 16-bit value; out: a 2-byte buffer.

Output format

None; out[0] is set to the high byte of x and out[1] to the low byte.

Constraints

Write bytes explicitly (big-endian) so the result is host-independent.

Starter code

void htons_bytes(unsigned short x, unsigned char *out) {
    /* TODO */
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.