Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print 0x0a instead of 0xa using cout?

How can I print 0x0a, instead of 0xa using cout?

#include  <iostream>  using std::cout;   using std::endl;   using std::hex;  int main()   {       cout << hex << showbase << 10 << endl;   } 
like image 568
Ayrosa Avatar asked Apr 22 '11 21:04

Ayrosa


People also ask

What is STD hex?

std::hex : When basefield is set to hex, integer values inserted into the stream are expressed in hexadecimal base (i.e., radix 16). For input streams, extracted values are also expected to be expressed in hexadecimal base when this flag is set.


2 Answers

This works for me in GCC:

#include  <iostream> #include  <iomanip>  using namespace std;  int main() {     cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl; } 

If you are getting sick and tired of iostream's formatting quirkiness, give Boost.Format a try. It allows good-old-fashioned, printf-style format specifiers, yet it is type-safe.

#include <iostream> #include <boost/format.hpp>  int main() {     std::cout << boost::format("0x%02x\n") % 10; } 

UPDATE (2019)

Check out the {fmt} library that's been accepted into C++20. Benchmarks show it to be faster than Boost.Format.

#if __has_include(<format>)     #include <format>     using std::format; #else     #include <fmt/format.h>     using fmt::format; #endif  std::cout << format("{:#04x}\n", 10); 
like image 198
Emile Cormier Avatar answered Sep 20 '22 16:09

Emile Cormier


Use setw and setfill from iomanip

#include  <iostream> #include  <iomanip>  using std::cout;   using std::endl;   using std::hex;  int main() {     cout << "0x" << std::setfill('0') << std::setw(2) << hex << 10 << endl; } 

Personally, the stateful nature of iostreams always annoys me. I think boost format is a better option, so I'd recommended the other answer.

like image 31
Doug T. Avatar answered Sep 22 '22 16:09

Doug T.