networking · beginner · ~15 min

Port from network bytes

Reassemble a 16-bit big-endian port.

Challenge

A port number is stored big-endian (network byte order) in a sockaddr. Reassemble the 16-bit port from its two bytes.

Task

Implement int port_from_be(unsigned char hi, unsigned char lo) that returns the port value (hi << 8) | lo, where hi is the most significant byte.

Input

  • hi: the high (most significant) byte.
  • lo: the low byte.

Output

Returns the reassembled 16-bit port value.

Example

port_from_be(0x00, 0x50)   ->   80
port_from_be(0x1f, 0x90)   ->   8080
port_from_be(0xff, 0xff)   ->   65535

Edge cases

  • The maximum value 0xff,0xff is 65535.

Input format

Two unsigned char bytes: hi (most significant) and lo.

Output format

The 16-bit port value (hi << 8) | lo.

Constraints

Network byte order is big-endian: hi is the most significant byte.

Starter code

int port_from_be(unsigned char hi, unsigned char lo) {
    /* TODO */
    return 0;
}

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