endianint.hpp: endianness-maintaining integers in 100 lines of C++(20)

submited by
Style Pass
2024-10-26 23:00:05

Oasis’ virtio spec, Section 1.4 defines the endian-specific types le16, le32, le64 to be little-endian unsigned integers. Likewise for be16, be32 and be64. I was perusing this because I wanted to make my own userspace networking drivers which I could run on a virtual machine. Practically every machine you could choose to run a VM on today is little endian, and you would have to go out of your way to test that your code runs on big endian machines. Ergo, it would have been good enough to do using le16 = uint16_t and move on.

We want to create a templated type which would take endianness and size of the integer as it’s parameters. The main requirements of this type are:

Here’s the 16-bit implementation. The 32 and 64-bit implementations are very similar but have a longer byteswap, so I’ve omitted them for clarity.

<bit> is a C++20 feature: this header enables the endian enum, and the native endian checks. My guess is it would be possible to package this up and ship it with the header for non-C++20 platforms, but I haven’t looked into it yet.

Leave a Comment