networking · beginner · ~15 min

Port to network bytes

Serialise a port in network byte order.

Challenge

Serialise a port number into two big-endian bytes — the wire form (what htons produces conceptually).

Task

Implement void port_to_be(int port, unsigned char *out) that writes port as two big-endian bytes: the high byte into out[0] and the low byte into out[1].

Input

  • port: the port value to serialise.
  • out: a buffer of at least 2 bytes.

Output

No return value. out[0] receives the most significant byte, out[1] the least significant.

Example

port_to_be(8080, out)   ->   out[0]=0x1f, out[1]=0x90
port_to_be(80, out)     ->   out[0]=0x00, out[1]=0x50

Edge cases

  • Mask each byte with & 0xFF after shifting.

Input format

An int port and a writable buffer out of at least 2 bytes.

Output format

No return value; out[0] = high byte, out[1] = low byte.

Constraints

Big-endian: out[0] = (port >> 8) & 0xFF, out[1] = port & 0xFF.

Starter code

void port_to_be(int port, unsigned char *out) {
    /* TODO */
}

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