networking · intermediate · ~15 min
Serialise a 16-bit value to network order.
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.
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.
x: a 16-bit value.out: a 2-byte buffer to write into.None (void). After the call, out[0] = high byte of x, out[1] = low byte of x.
htons_bytes(0x1234, out) -> out = {0x12, 0x34}
htons_bytes(80, out) -> out = {0x00, 0x50}
x: a 16-bit value; out: a 2-byte buffer.
None; out[0] is set to the high byte of x and out[1] to the low byte.
Write bytes explicitly (big-endian) so the result is host-independent.
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.