Armen Tsirunyan
Armen Tsirunyan

Reputation: 133054

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.

Upvotes: 11

Views: 310

Answers (2)

vitaut
vitaut

Reputation: 55595

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("{:X}\n", 0xABC);  

Output:

ABC

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("{:X}\n", 0xABC); 

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881893

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

Upvotes: 12

Related Questions