Avoid macros when you can! They hide the code, making debugging difficult, do not take into account the scope, etc.
You can use the simple function provided by KenE. If you want to get everything fancy and flexible, then you can write your own manipulator:
#include <iostream> #include <iomanip> using namespace std; ostream& hex4(ostream& out) { return out << "0x" << hex << setw(4) << setfill('0'); } int main() { cout << hex4 << 123 << endl; }
This makes it a little more general. The reason the above function can be used is because operator<< already overloaded as follows: ostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&)) . endl and some other manipulators are also implemented as follows.
If you want to allow the indication of the number of digits at runtime, we can use the class:
#include <iostream> #include <iomanip> using namespace std; struct formatted_hex { unsigned int n; explicit formatted_hex(unsigned int in): n(in) {} }; ostream& operator<<(ostream& out, const formatted_hex& fh) { return out << "0x" << hex << setw(fh.n) << setfill('0'); } int main() { cout << formatted_hex(4) << 123 << endl; }
If size can be determined at compile time, however, maybe just use a function template [thanks Jon Purdy for this suggestion]:
template <unsigned int N> ostream& formatted_hex(ostream& out) { return out << "0x" << hex << setw(N) << setfill('0'); } int main() { cout << formatted_hex<4> << 123 << endl; }
stinky472
source share