且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将uint64转换为(完整)十六进制字符串,C ++

更新时间:2023-02-03 08:42:07

您可以使用IO操作符:

  #include< iomanip& 
#include< iostream>

std :: cout<< std :: setw(16)<< std :: setfill('0')<< std :: hex<< X;或者,您可以在 std :: cout 上单独更改格式化标志, / code>与 std :: cout.setf(std :: ios :: hex)等,例如请参阅此处(格式设置)。请注意,字段宽度必须每次都设置,因为它只影响下一个输出操作,然后恢复为默认值。

要获取真正的十六进制数字在平***立的方式,你可以说像 sizeof(T)* CHAR_BIT / 4 +(sizeof(T)* CHAR_BIT%4 == 0?0:1)作为 setw 的参数。


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.