Search code examples
c++bitstd-byte

How to create an octet type similar to std::byte in C++?


The type std::byte comprises CHAR_BIT bits, and that may be more than 8.

So, how do I declare a true octet in C++?


Solution

  • If the hardware supports 8-bit integers with no padding, then std::uint8_t will be defined, and could be used for that purpose.

    enum class octet : std::uint8_t {};
    
    // add bitwise ops similar to the operator overloads for std::byte
    // alternatively, use std::uint8_t directly
    

    However, this is basically pointless. If unsigned char is wider than 8 bits, then std::uint8_t won't be defined because no type can be smaller than a byte in C++.

    Any "true octet" type is either not going to be portable, or it will require padding. If padding is acceptable, you can define it as follows:

    enum class octet : std::uint_least8_t {};
    
    constexpr bool operator==(octet x, octet y) noexcept {
        return (unsigned(x) & 0xff) == (unsigned(y) & 0xff);
    }
    
    // TODO: implement other comparisons
    
    constexpr octet operator|(octet x, octet y) noexcept {
        return octet(unsigned(x) | unsigned(y));
    }
    
    constexpr octet operator<<(octet x, std::integral auto s) noexcept {
        return octet((unsigned(x) << s) & 0xff);
    }
    
    // TODO: implement other bitwise ops, and possibly arithmetic ops
    

    Also, as commenters have pointed out, hardware with no support for 8-bit types is extremely rare. Unless you expect to compile your code for digital signal processors (DSPs) or other unusual hardware, just assume 8-bit bytes. Use std::uint8_t, or

    static_assert(CHAR_BIT == 8);