11

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.

paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
Armen Tsirunyan
  • 120,726
  • 52
  • 304
  • 418
  • 2
    Could the downvoter of this question please be so kind as to explain to me what is so criminal about this question? As a matter of fact, I had opened MSDN for 'hex' in hopes to find the answer, but I didn't. So what's wrong with this question? – Armen Tsirunyan Nov 07 '10 at 09:39
  • Don't know, but here's a upvote to counter it. I love doing that because it's fair (especially to those who have a genuine question - SO is meant to be for _all_ levels of developer, not just obnoxious know-it-alls like me) but mostly because it annoys the drive-by downvoters who can't even be bothered to leave a comment so that a question can be improved. Of course, they may well downvote my answer in retribution but it's not like I'm short of rep :-) – paxdiablo Nov 07 '10 at 09:50
  • @paxdiablo: my feeling about retaliatory downvotes is that anyone likely to get involved in such nonsense has less than half my rep, so I'm going to win that one. Since I have less than half your rep, you can outlast twice as many... – Steve Jessop Nov 07 '10 at 10:38

2 Answers2

12

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
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
1

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.

vitaut
  • 37,224
  • 19
  • 144
  • 248