开发者

printing negative value in C++ base 8 or 16

开发者 https://www.devze.com 2023-04-03 19:45 出处:网络
How is C++ supposed to print negative values in base 8 or 16? I know I can try what my current compiler/library does (it 开发者_开发百科prints the bit pattern, without a minus in front) but I want to

How is C++ supposed to print negative values in base 8 or 16? I know I can try what my current compiler/library does (it 开发者_开发百科prints the bit pattern, without a minus in front) but I want to know what is should do, preferrably with a reference.


It seems that none of the standard output facilities support signed formatting for non-decimals. So, try the following workaround:

struct signprint
{
  int n;
  signprint(int m) : n(m) { }
};

std::ostream & operator<<(std::ostream & o, const signprint & s)
{
  if (s.n < 0) return o << "-" << -s.n;
  return o << s.n;
}

std::cout << std::hex << signprint(-50) << std::endl;

You can insert an 0x in the appropriate location if you like.


From §22.2.2.2.2 (yes, really) of n1905, using ios_base::hex is equivalent to the stdio format specifier %x or %X.

From §7.21.6.1 of n1570, the %x specifier interprets its argument as an unsigned integer.

(Yes, I realize that those are wacky choices for standards documents. I'm sure you can find the text in your favorite copy if you look hard enough.)

0

精彩评论

暂无评论...
验证码 换一张
取 消