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.
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.)
精彩评论