簡體   English   中英

將uint64轉換為(完整)十六進制字符串,C ++

[英]Converting an uint64 into a (full)hex string, C++

我一直在嘗試將uint64數字轉換為十六進制格式的字符串。 但是它應該包括零。 例:

uint i = 1;
std::ostringstream message;
message << "0x" << std::hex << i << std::dec;
...

這將生成:

0x1

但這不是我想要的。 我想要:

0x0000000000000001

還是uint64需要多個零。

您可以使用IO機械手:

#include <iomanip>
#include <iostream>

std::cout << std::setw(16) << std::setfill('0') << std::hex << x;

或者,您可以使用std::cout.setf(std::ios::hex)等在std::cout上分別更改格式標志,例如, 請參見此處(“格式設置”) 請注意,每次必須設置字段寬度,因為它只會影響下一個輸出操作,然后恢復為默認值。

要以獨立於平台的方式獲取十六進制數字的真實數目,可以說像sizeof(T) * CHAR_BIT / 4 + (sizeof(T)*CHAR_BIT % 4 == 0 ? 0 : 1)作為setw的參數。

message << "0x" << std::setfill('0') << std::setw(12) << std::hex << i << std::dec;

並使用Boost保存和恢復流的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM