c++插入到具有十六进制格式的流中

c++ insert to a stream with formatting for hex

本文关键字:格式 十六进制 插入 c++      更新时间:2023-10-16

我经常做这样的事情:

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';
  1. 调用hexb(c)并返回一个hexcdumper,其构造函数保存c
  2. 过载运算符<lt;对于hexcdumper调用hexcdumper::operator()将流传递给它
  3. hexcdumper的运算符()为我们发挥了所有的魔力
  4. 在hexcdumper::operator()返回后,重载的运算符<lt;返回从hexcdumper::operator()返回的流,以便进行链接

在输出上,我看到:

0x0e

有更简单的方法吗?

Patrick

您可以直接在流管道上执行此操作:

std::cout << "Hex = 0x" << hex << 14 << ", decimal = #" << dec << 14 << endl;

输出:

Hex = 0xe, decimal = #14