什么可以改变显示宽度?

时间:2017-07-24 18:14:23

标签: c++ formatting systemc

我有一个带签名的函数(实际上是SystemC)

sc_dt::sc_uint<12> Get()

和行

  cerr << "[" << hex << setw(3) << setfill('0') << 0 << dec << "]\n";
  cerr << "[" << hex << setw(3) << setfill('0') << Get() << dec << "]\n";

导致输出

[000]
[0000]

为什么显示的宽度从3变为4?

1 个答案:

答案 0 :(得分:3)

#include <systemc.h>
#include <iostream>
#include <iomanip>

int sc_main(int argc, char* argv[])
{
    sc_dt::sc_uint <12> my_uint = 0;
    std::cerr << std::hex << my_uint << std::endl;
}

g++ test.cpp -lsystemc && ./a.out打印出来:

        SystemC 2.3.1-Accellera --- Jul 24 2017 21:50:41
        Copyright (c) 1996-2014 by all Contributors,
        ALL RIGHTS RESERVED
0000

它显示四个零(对于16位)而不是三个(对于12位),正如您可能预期的那样,因为这是在SystemC中实现12位整数的方式。它不会被std::setw缩短,因为它会设置要写入的最小数字。如果有更多的字符,那么所有字符都将被写入。另外,您的示例中的std::dec什么都不做,因为之后没有打印过数字。

http://www.cplusplus.com/reference/ios/ios_base/width/
http://www.cplusplus.com/reference/iomanip/setw/

这将为低12位仅打印最后3个字符:

#include <systemc.h>
#include <iostream>
#include <iomanip>

const unsigned CHARS  = 3;
const unsigned MASK   = (1u << CHARS * 4) -1; // Same as 0xFFF

int sc_main(int argc, char* argv[])
{
    sc_dt::sc_uint <12> my_uint = 0xABC;
    std::cerr << std::hex
              << std::setw (CHARS) << std::setfill ('0')
              << (my_uint & MASK) << std::endl;
}