简体   繁体   中英

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., eg 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;

并使用Boost保存和恢复流的状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM