如果硬件支持无填充的 8 位整数,则将std::uint8_t被定义,并可用于该目的。
enum class octet : std::uint8_t {};
// add bitwise ops similar to the operator overloads for std::byte
// alternatively, use std::uint8_t directly
Run Code Online (Sandbox Code Playgroud)
然而,这基本上是没有意义的。如果unsigned char比 8 位宽,则std::uint8_t不会被定义,因为在 C++ 中没有类型可以小于字节。
任何“真正的八位字节”类型要么不可移植,要么需要填充。如果填充可以接受,您可以将其定义如下:
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
Run Code Online (Sandbox Code Playgroud)
此外,正如评论者所指出的,不支持 8 位类型的硬件极为罕见。除非您希望为数字信号处理器 (DSP) 或其他不常见的硬件编译代码,否则请假设 8 位字节。使用std::uint8_t, 或
static_assert(CHAR_BIT == 8);
Run Code Online (Sandbox Code Playgroud)