什么可以改变显示宽度?

What could change display width?

我有一个带有签名的 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?

#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;
}