代码之家  ›  专栏  ›  技术社区  ›  Peter.O

ostream showbase不为零值显示“0x”

  •  10
  • Peter.O  · 技术社区  · 15 年前

    PSP: (预先编写的后记)

    一切都开始于一个愉快的星期天早晨。。。我想在十六进制表示中转储一些句柄 一致,格式化 是的。
    前导0x 和一个 固定宽度 ,但事实证明,使用预期的流操纵器很难做到这一点。
    这似乎有点不合理,我想我不是唯一一个想要这个的人。。
    我错过什么了吗

    我不想把事情搞得一团糟。
    我不想硬编码“0x”前缀。有没有一种方法可以使用标准的操纵器?或者我需要让ostream的手柄过载(但那会让我超负荷的!)

    这是我的测试代码(及其输出)。
    为了清楚起见,我使用了“.”作为填充字符(实际上我将使用“0”)

    HANDLE h; 
    ULONG ul; 
    int iH = sizeof(h); // how many bytes to this void* type.
    int iW = iH*2;      // the max number of hex digits (width).
    int iW2= iW+2;      // the max number of hex digits (+ 2 for showbase "0x").
    int iX = 4;         // the number of bits per hex digit.
    int ib = iH*8;      // the max number bits in HANDLE (exponent).
    int i;
    std::cout<<std::setfill('.'); // I actually want '0'; 
                                  //   the dot is for display clarity
    for( i=0; i<=ib; i+=iX )
    { ul = (pow(2,i)-1);
      h  = (HANDLE)ul;
      std::cout
      <<"//  ul "        <<std::setw(iW2)<<std::hex <<std::showbase  <<std::internal <<ul
      <<"     h "        <<std::setw(iW2) /* hex,showbase,internal have no effect */ <<h
      <<"      I want 0x"<<std::setw(iW) <<std::hex <<std::noshowbase<<std::right    <<(ULONG)h
      <<std::endl;
    }
    
    //  ul .........0     h .........0      I want 0x.......0
    //  ul 0x.......f     h .......0xf      I want 0x.......f
    //  ul 0x......ff     h ......0xff      I want 0x......ff
    //  ul 0x.....fff     h .....0xfff      I want 0x.....fff
    //  ul 0x....ffff     h ....0xffff      I want 0x....ffff
    //  ul 0x...fffff     h ...0xfffff      I want 0x...fffff
    //  ul 0x..ffffff     h ..0xffffff      I want 0x..ffffff
    //  ul 0x.fffffff     h .0xfffffff      I want 0x.fffffff
    //  ul 0xffffffff     h 0xffffffff      I want 0xffffffff
    
    2 回复  |  直到 6 年前
        1
  •  11
  •   George    15 年前

    我发现这个 https://bugzilla.redhat.com/show_bug.cgi?id=166735 -这是直接从那里复制/粘贴。

    听起来不像虫子。 ISO C++ 98,22.2.2.2.2/10表示STD:SkyBASE意味着提前打印 限定符。22.2.2.2.2/7表示std::hex表示printf转换说明符为 %十。 但是 http://www.opengroup.org/onlinepubs/009695399/functions/fprintf.html 对于x或x转换说明符,非零结果应具有0x(或0x) 以它为前缀。” ISO C99,7.19.6.1(6)中也有相同规定: 对于x(或x)转换,非零结果的前缀为0x(或0x)

    所以听起来像C++ 98标准(说)“让它像C的PrPtf(“%x x”,0))需要你看到的这种愚蠢的行为。获得所需内容的唯一方法是显式地除去std::showbase和输出0x。对不起的。

        2
  •  7
  •   Sliq    15 年前

    当值为零时,std::showbase没有“0x”这一事实有时令人恼火,但这就是它的定义方式,除了:

    std::cout << "0x" << .....
    

    “0x”和其余部分之间的差距是可以修复的,但这并不容易猜测。尝试

    std::cout << std::hex << std::showbase << std::setw(8) << std::setfill('0') << h;