networking · intermediate · ~15 min

Unpack a 32-bit address

Decode sin_addr back into octets.

Challenge

The reverse of packing: split a 32-bit big-endian IPv4 address back into its four octets.

Task

Implement void be32_to_ipv4(unsigned addr, int *a, int *b, int *c, int *d) that writes the four octets of addr into the output pointers, with *a taking the most-significant byte.

Input

  • addr: the packed 32-bit address.
  • a, b, c, d: out-pointers for the four octets.

Output

No return value. *a = (addr >> 24) & 0xFF, ..., *d = addr & 0xFF.

Example

be32_to_ipv4(0x7F000001, ...)   ->   a=127, b=0,   c=0, d=1
be32_to_ipv4(0xC0A80001, ...)   ->   a=192, b=168, c=0, d=1

Input format

A packed 32-bit address addr and four out-pointers a, b, c, d.

Output format

No return value; each octet is written to its pointer, a = most-significant byte.

Constraints

Extract each octet with a right shift and mask 0xFF.

Starter code

void be32_to_ipv4(unsigned addr, int *a, int *b, int *c, int *d) {
    /* TODO */
}

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