Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 616
Armen Tsirunyan Avatar asked Nov 07 '10 09:11

Armen Tsirunyan


2 Answers

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.

like image 131
vitaut Avatar answered Oct 13 '22 20:10

vitaut


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
like image 43
paxdiablo Avatar answered Oct 13 '22 20:10

paxdiablo