c++插入到具有十六进制格式的流中
c++ insert to a stream with formatting for hex
我经常做这样的事情:
uint8_t c=some_value;
std::cout << std::setfill('0') << std::setw(2);
std::cout << std::hex << int(c);
std::cout << std::setfill(' ');
(尤其是在转储调试信息时)。如果我能把一些操纵性的东西放在这样的流中,那不是很好吗:
std::cout<lt;"c值:0x"<lt;hexb(c)<lt;'\n';
那就行了?有人知道怎么做吗?
我已经做到了,但我想有一个更简单的方法:
#include <iostream>
#include <iomanip>
class hexcdumper{
public:
hexcdumper(uint8_t c):c(c){};
std::ostream&
operator( )(std::ostream& os) const
{
// set fill and width and save the previous versions to be restored later
char fill=os.fill('0');
std::streamsize ss=os.width(2);
// save the format flags so we can restore them after setting std::hex
std::ios::fmtflags ff=os.flags();
// output the character with hex formatting
os << std::hex << int(c);
// now restore the fill, width and flags
os.fill(fill);
os.width(ss);
os.flags(ff);
return os;
}
private:
uint8_t c;
};
hexcdumper
hexb(uint8_t c)
{
// dump a hex byte with width 2 and a fill character of '0'
return(hexcdumper(c));
}
std::ostream& operator<<(std::ostream& os, const hexcdumper& hcd)
{
return(hcd(os));
}
当我这样做时:
std::cout << "0x" << hexb(14) << 'n';
- 调用hexb(c)并返回一个hexcdumper,其构造函数保存c
- 过载运算符<lt;对于hexcdumper调用hexcdumper::operator()将流传递给它
- hexcdumper的运算符()为我们发挥了所有的魔力
- 在hexcdumper::operator()返回后,重载的运算符<lt;返回从hexcdumper::operator()返回的流,以便进行链接
在输出上,我看到:
0x0e
有更简单的方法吗?
Patrick
您可以直接在流管道上执行此操作:
std::cout << "Hex = 0x" << hex << 14 << ", decimal = #" << dec << 14 << endl;
输出:
Hex = 0xe, decimal = #14
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- 以C++格式将十六进制字符串转换为十进制数
- TCP/IP - 以 C/C++ 格式发送十六进制数据包以控制中继板
- 计算 RSA 并以十六进制格式保存到文件
- 以十六进制格式表示 fp16 最小数
- 将字符串转换为十六进制格式并将"0x "附加到十六进制值
- 需要在 c++ 中以十六进制格式将字符串写入文件
- 使用字符串格式限制十六进制数字的数量
- 如何从字符中读取ASCII值并将其转换为十六进制格式的字符串
- C++为什么字符串的地址尽管是十六进制格式,但不能存储在 long int 变量中?
- 在缓冲区中以十六进制格式插入一个值
- 以相同的格式将十六进制字符串转换为int
- 如何使用十六进制格式更改容器的背景颜色
- 将指纹(十六进制格式)转换为图像
- 如何使用c++从字符串中检索十六进制格式的字节值
- 提升::格式十六进制中的奇怪行为
- 将十六进制字节值转换为 DWORD (ascii) 格式
- c++插入到具有十六进制格式的流中
- 在c++中使用cout以十六进制格式打印OpenCL cl_uchar