[英]C++ converting vector to 2 hex and then store it in a string
我主要使用C語言,所以我對C ++還是很陌生。 我想將int向量(std :: vector)轉換為十六進制表示形式,然后將其存儲到字符串中。 我在以下線程中找到了可以在C中使用的東西: 使用'sprintf'將十六進制轉換為字符串
user411313提出的代碼如下:
static unsigned char digest[16];
static unsigned char hex_tmp[16];
for (i = 0; i < 16; i++) {
printf("%02x",digest[i]);
sprintf(&hex_tmp[i], "%02x", digest[i]);
}
我擔心的一個問題是,由於sprintf可能會嘗試在內容后添加0,因此這可能會超出索引。 另外,我想知道是否可以使用本機C ++進行任何操作,也許可以使用任何內置函數代替C函數。 在c ++中,這比c函數更可取嗎? 非常感謝你的協助!
如果可以使用本機C ++進行任何處理,則可以使用任何內置函數代替C函數。 在c ++中,這比c函數更可取嗎?
當然有辦法,是更好的選擇:
static std::array<unsigned char,16> digest;
static std::string hex_tmp;
for (auto x : digest) {
std::ostringstream oss;
oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned)x;
hex_tmp += oss.str();
}
我擔心的一個問題是,由於sprintf可能會嘗試在內容后添加0,因此這可能會超出索引。
這是一個有效的擔憂。 上面我的代碼片段中使用的類將克服所有這些問題,您無需關心。
您可以使用std::stringstream
std::string hex_representation(const std::vector<int>& v) {
std::stringstream stream;
for (const auto num : v) {
stream << "0x" << std::hex << std::setw(2) << std::setfill('0') << num
<< ' ';
}
return stream.str();
}
顯然,如果不需要,您可以刪除"0x"
前綴
這里有現場演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.