9

I know how to cause it to be in hex:

unsigned char myNum = 0xA7;
clog << "Output: " std::hex << int(myNum) << endl;
// Gives:
//   Output: A7

Now I want it to always print a leading zero if myNum only requires one digit:

unsigned char myNum = 0x8;
// Pretend std::hex takes an argument to specify number of digits.
clog << "Output: " << std::hex(2) << int(myNum) << endl;
// Desired:
//   Output: 08

So how can I actually do this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
WilliamKF
  • 41,123
  • 68
  • 193
  • 295

5 Answers5

14

It's not as clean as I'd like, but you can change the "fill" character to a '0' to do the job:

your_stream << std::setw(2) << std::hex << std::setfill('0') << x;

Note, however, that the character you set for the fill is "sticky", so it'll stay '0' after doing this until you restore it to a space with something like your_stream << std::setfill(' ');.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

This works:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int x = 0x23;
  cout << "output: " << setfill('0') << setw(3) << hex << x << endl;
}

output: 023

jterrace
  • 64,866
  • 22
  • 157
  • 202
1
glog << "Output: " << std::setfill('0') << std::hex(2) << int(myNum) << endl;

See also: http://www.arachnoid.com/cpptutor/student3.html

levis501
  • 4,117
  • 23
  • 25
1

Take a look at the setfill and setw manipulators in <iomanip>

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

It is a little bit dirty, but a macro did a good job for me:

#define fhex(_v) std::setw(_v) << std::hex << std::setfill('0')

So then you can do it:

#include <iomanip>
#include <iostream>
...
int value = 0x12345;
cout << "My Hex Value = 0x" << fhex(8) << value << endl;

The output:

My Hex Value = 0x00012345

marcelo.guedes
  • 482
  • 5
  • 12