how to format hex numbers using stringstream

mtijn picture mtijn · Aug 5, 2014 · Viewed 43.9k times · Source

I am trying to convert an unsigned short to its hexadecimal representation in uppercase and prefixed with 0's using stringstream. I can't seem to get the uppercase and 0's correct. here is what I have now:

USHORT id = 1127;
std::stringstream ss;
ss << std::showbase << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id;
std::string result = ss.str();

this results in the prefixed '0x' base also being uppercase but I want that to be lowercase. it also results in no prefixed 0's to the hexadecimal value after the prefixed 0x base (currently 0X). for example, this will now output 0X467 instead of the expected 0x0467. how do I fix this?

Answer

Praetorian picture Praetorian · Aug 5, 2014

setw is going to set the width of the entire formatted output, including the displayed base, which is why you're not seeing the leading 0. Also, there's no way to make the base be displayed in lowercase if you use std::showbase along with std::uppercase. The solution is to insert the base manually, and then apply the remaining manipulators.

ss << "0x" << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id;

This outputs 0x0467