C++ 使用ostream格式化自定义类型
我们可以使用不同的选项更改流行为:C++ 使用ostream格式化自定义类型,c++,ostream,C++,Ostream,我们可以使用不同的选项更改流行为: std::cout << 0xfabadau << '\n'; std::cout << std::hex << std::setfill('0') << std::setw(8) << 0xfabadau << '\n'; 现在让我们假设我有一个字节缓冲区自定义类型: using byte = std::uint8_t; using byte_buffer =
std::cout << 0xfabadau << '\n';
std::cout << std::hex << std::setfill('0') << std::setw(8) << 0xfabadau << '\n';
现在让我们假设我有一个字节缓冲区
自定义类型:
using byte = std::uint8_t;
using byte_buffer = std::vector<byte>;
std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
{
for (const auto &b : buffer) o << std::hex << int{b};
return o << std::dec;
}
std::setfill
和std::setw
在std::ostream&operator之外,您可以使用类似这样的字节
std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
{
std::uint32_t temp=0;
for (const auto &b : buffer)
{
temp<<=8;
temp|=b;
}
return o << std::hex << temp << std::dec;
}
std::ostream&operator您可以随时获取标志,并在函数中使用它们。例如(此处仅处理宽度)
int width=o.width(),项目宽度;
int fill=o.fill();
如果(宽度>2*buffer.size())
项目宽度=宽度-2*(buffer.size()-1);
其他的
项目宽度=2;
用于(常数自动&b:缓冲区)
{
o这是一种非常有趣的方法:)但它不能处理任意长度的缓冲区(想象一个长度大于4,8,16666的byte\u缓冲区
)。
byte_buffer b { 0xfau, 0xbau, 0xdau, };
std::cout << b << '\n';
std::cout << std::hex << std::setfill('0') << std::setw(8) << b << '\n';
fabada
000000fabada
fabada
00fabada
std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
{
std::uint32_t temp=0;
for (const auto &b : buffer)
{
temp<<=8;
temp|=b;
}
return o << std::hex << temp << std::dec;
}
std::ostream &operator <<(std::ostream &o, const byte_buffer &buffer)
{
std::ostringstream ss;
for (const auto &b : buffer)
{
ss<< std::hex << int{b};
}
return o << ss.str();
}
int width = o.width(), item_width;
int fill = o.fill();
if (width > 2*buffer.size())
item_width = width - 2*(buffer.size()-1);
else
item_width = 2;
for (const auto &b : buffer)
{
o << std::hex << std::setw(item_width) << setfill(fill) << int{b};
item_width = 2; fill = '0';
}