At one time, we had to constantly work with network data, and especially with the headings of the network and transport layers of the OSI model. Constantly strained by the fact that many fields were in the Big-Endian, and the code was executed on the architecture of Little-Endian. Well, it was impossible to constantly call
ntohl (), htonl (), ntohs (), htons () ...

Photo author:
Ciroduran , photo source:
flickr .
The idea came to implement the following pair of patterns: LittleEndian <T> and BigEndian <T>.
')
Template for byte order LittleEndian:

Template for the BigEndian byte order:

Templates are used as follows:

It remains to give the types more nice names, like this:

Now you can use types through shorter names
u16be ,
u32be ...
The only thing in these templates is not enough different operators + =, - =, * =, ++ and others. Operators are available in the full version of the code, it was inappropriate to bring them into the article. Here are links to the complete source codes
LittleBigEndian.h (see the new link below in UPDATE1) and
LittleBigEndianNames.h .
UPDATE1:As was
rightly noted by the user
qehgt in the comment to the post, the code is not quite correct for 64-bit numbers. I apologize for this misstep. Here is
LittleBigEndian.h (see the new link below in UPDATE3) where this bug has been fixed.
UPDATE2:Comrade
sic conducted
tests of the speed of the above templates in comparison with the functions htohl (), htonl (), ntohs (), htons (). Tests showed a relative increase in speed when using the above templates instead of calling library functions. Thanks for the work you've done.
UPDATE3:Comrade
rekub saw the possibility of increasing the speed of the object copy constructor. He
proposed using union to represent data both as an array and as a variable of type T. The proposed modifications were implemented in the following source,
LittleBigEndian.h (see the new link below in UPDATE4). Thank!
UPDATE4:Comrade
vadelve pointed out an error in the implementation of postfix and prefix increment and decrement operators. Corrected version:
LittleBigEndian.h .