Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a manipulator to format my hex output with padded left zeros

The little test program below prints out:

And SS Number IS =3039

I would like the number to print out with padded left zeros such that the total length is 8. So:

And SS Number IS =00003039 (notice the extra zeros left padded)

And I would like to know how to do this using manipulators and a stringstream as shown below. Thanks!

The test program:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{

    int i = 12345;
    std::stringstream lTransport;

    lTransport << "And SS Number IS =" << std::hex << i << '\n';

    std::cout << lTransport.str();

}
like image 422
bbazso Avatar asked Mar 02 '10 19:03

bbazso


2 Answers

Have you looked at the library's setfill and setw manipulators?

#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';

The output I get is:

And SS Number IS =00003039
like image 142
Dr. Watson Avatar answered Oct 01 '22 20:10

Dr. Watson


I would use:

cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
like image 26
Šimon Tóth Avatar answered Oct 01 '22 19:10

Šimon Tóth