networking · intermediate · ~15 min

ntohs via bytes

Deserialise a 16-bit value from network order.

Challenge

Read a 16-bit value back from two network-order (big-endian) bytes — the inverse of writing them out.

Task

Implement unsigned short ntohs_bytes(const unsigned char *in) that reads in[0] (high byte) and in[1] (low byte) into a 16-bit host value.

Input

  • in: a 2-byte buffer in big-endian order.

Output

The reconstructed 16-bit value: (in[0] << 8) | in[1].

Example

{0x12, 0x34}  ->  0x1234
{0x00, 0x50}  ->  80

Input format

in: a 2-byte buffer in big-endian order.

Output format

The 16-bit value (in[0]<<8)|in[1].

Constraints

The first byte is most significant.

Starter code

unsigned short ntohs_bytes(const unsigned char *in) {
    /* TODO */
    return 0;
}

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