c++ 17引入了 一种std::byte类型,它表示内存元素的“nature”类型字节。与char或int类型的关键区别在于,它不是字符类型且非算术类型,它唯一支持的“计算”操作是位操作符。
1.std::byte的使用
补充知识:
1)一个byte(字节)为八位二进制,可以存储十进制数值0-255
2)0x为十六进制,0b为二进制
3)位运算:
#include <cstddef> // for std::byte
std::byte b1{0x3F};//
std::byte b2{0b1111'0000};
std::byte b4[4] {b1, b2, std::byte{1}}; // 4 bytes (last is 0)
if (b1 == b4[0])
{
b1 <<= 1;
}
std::cout << std::to_integer<int>(b1) << '\n'; // outputs: \T{126}
//列表初始化(使用大括号)是直接初始化std::byte对象的单个值的唯一方法。
std::byte b1{42}; // OK (as for all enums with fixed underlying type since C++17)
std::byte b2(42); // ERROR
std::byte b3 = 42; // ERROR
std::byte b4 = {42}; // ERROR
初始化及相关用法如下:
//须用显式转换的整数文字初始化字节数组
std::byte b5[] {1}; // ERROR
std::byte b5[] {std::byte{1}}; // OK
//如果不进行任何初始化,std::byte的值将为堆栈上的对象未定义
std::byte b; // undefined value
//可以强制初始化,所有的位都设置为零,并使用列表初始化
std::byte b{}; // same as bf0g
//std::byte作为布尔值也需要这样的转换
if (b2) ... // ERROR
if (b2 != std::byte{0}) ... // OK
if (to_integer<bool>(b2)) ... // ERROR (ADL doesn’t work here)
if (std::to_integer<bool>(b2)) ... // OK
1.std::byte的操作
例子
#include <iostream>
#include <string>
#include <cstddef>
#include <bitset>
#include <limits>
int main()
{
std::byte b1{ 0x3F };
std::byte b2{ 0b1111'0000 };
std::byte b4[4]{ b1, b2, std::byte{1} }; // 4 bytes (last is 0)
std::byte b5[]{ std::byte{1} };
std::byte b6{};
if (b2 == std::byte{ 0b1111'0000 })
{
std::cout << std::to_integer<int>(b2) << std::endl;
}
using ByteBitset = std::bitset<std::numeric_limits<unsigned char>::digits>;
std::cout << ByteBitset{ std::to_integer<unsigned char>(b1) } << std::endl;
std::string s = ByteBitset{ std::to_integer<unsigned char>(b2) }.to_string();
std::cout << s << std::endl;
return 0;
}