Converting an uint64 into a (full)hex string, C++
I've been trying to get a uint64
number into a string, in hex format. But it should include zeros.开发者_如何学运维 Example:
uint i = 1;
std::ostringstream message;
message << "0x" << std::hex << i << std::dec;
...
This will generate:
0x1
But this is not what I want. I want:
0x0000000000000001
Or however many zeros a uint64
needs.
You can use IO manipulators:
#include <iomanip>
#include <iostream>
std::cout << std::setw(16) << std::setfill('0') << std::hex << x;
Alternatively, you can change the formatting flags separately on std::cout
with std::cout.setf(std::ios::hex)
etc., e.g. see here ("Formatting"). Beware that the field width has to be set every time, as it only affects the next output operation and then reverts to its default.
To get the true number of hex digits in a platform independent way, you could say something like sizeof(T) * CHAR_BIT / 4 + (sizeof(T)*CHAR_BIT % 4 == 0 ? 0 : 1)
as the argument for setw
.
message << "0x" << std::setfill('0') << std::setw(12) << std::hex << i << std::dec;
And use Boost to save and restore the state of the stream.
精彩评论