Converting the endianness

While serialization libraries deal with the endianness under the hood, there are situations where developers might want to implement a lightweight communication protocol themselves. 

While the C++ Standard Library does not provide functions for serialization, developers may utilize the fact that, in binary network protocols, byte order is defined and is always big-endian.

The Standard Library provides a set of functions that can be used for conversion between the current platform (hardware) and big-endian (network) byte orders:

  • uint32_t htonl (uint32_t value): Converts uint32_t from hardware to network order
  • uint32_t ntohl (uint32_t value): Converts uint32_t from network to hardware order
  • uint16_t htons (uint16_t value): Converts uint16_t from hardware to network order 
  • uint16_t ntohl (uint16_t value): Converts uint16_t from network to hardware order

Developers can use these functions to exchange binary data between applications running on different platforms.

In this recipe, we will learn how to encode strings so that they can be exchanged between two systems that may have the same or different endianness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.222