【问题标题】:c++ insert to a stream with formatting for hexc ++插入到具有十六进制格式的流中
【发布时间】:2013-07-17 01:37:48
【问题描述】:

我经常做这样的事情:

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

这一切都可以吗?有人知道怎么做吗?

我已经完成了这项工作,但希望有一个更简单的方法:

#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. 重载运算符
  3. hexcdumper 的 operator() 为我们做了所有的魔法
  4. hexcdumper::operator() 返回后,重载的操作符

在输出中,我看到:

0x0e

有没有更简单的方法来做到这一点?

帕特里克

【问题讨论】:

  • 您认为您的解决方案有什么问题?对我来说看起来不错,如果它可以满足您的需求。 优雅被夸大了!!

标签: c++ hex


【解决方案1】:

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

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

输出:

Hex = 0xe, decimal = #14

【讨论】:

  • 没错,但没有适当地设置填充或宽度,也没有在没有太多冗长的情况下恢复它们。问题只是关于如何避免重复冗长。而不是你的 0xe,我更喜欢 0x0e,或者如果我使用输出 3、7 和 14 字节的字符串流来执行此操作,我更喜欢 03070e 到 37e,这会令人困惑并且可能是错误的。到目前为止,我提出的解决方案也适用于字符串流。
猜你喜欢
  • 2011-06-01
  • 2011-12-09
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多