how to format hex numbers using stringstream

49,328

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

Share:
49,328
mtijn
Author by

mtijn

Updated on August 06, 2020

Comments

  • mtijn
    mtijn over 3 years

    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?

  • Zitrax
    Zitrax over 8 years
    Just to mention it std::internal can be used to get the fill chars between the base and the number (but does not help if you want different case of the base and number).