Wouter van Ooijen
Wouter van Ooijen

Reputation: 1039

printing negative value in C++ base 8 or 16

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.

Upvotes: 2

Views: 1859

Answers (2)

Dietrich Epp
Dietrich Epp

Reputation: 213308

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.)

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 476990

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.

Upvotes: 4

Related Questions