Search code examples
c++hexiostreamiomanip

How can I stream hexadecimal numbers with A-F (rather than a-f)?


Is it possible to make ostream output hexadecimal numbers with characters A-F and not a-f?

int x = 0xABC;
std::cout << std::hex << x << std::endl;

This outputs abc whereas I would prefer to see ABC.


Solution

  • Yes, you can use std::uppercase, which affects floating point and hexadecimal integer output:

    std::cout << std::hex << std::uppercase << x << std::endl;
    

    as in the following complete program:

    #include <iostream>
    #include <iomanip>
    
    int main (void) {
        int x = 314159;
        std::cout << std::hex << x << " " << std::uppercase << x << std::endl;
        return 0;
    }
    

    which outputs:

    4cb2f 4CB2F