在做一個專案時,我發現自己想知道如何從字串轉換為十六進制。不僅僅是從字串“42”轉換為十六進制 0x3432。
我很好奇您將如何將字串“0x42”轉換為十六進制 0x42。如,假設給定的字串是一個有效的十六進制數字(我知道這是一個很大的假設,但繼續吧......)。我想將其用作十六進制數字,而不是字串。我將如何進行這種轉換?
這不是我會做的事情......我只是更好奇它是否以及如何完成,因為直到現在我從未遇到過這種型別的問題。
*使用 C 和 C
uj5u.com熱心網友回復:
由于這只是相同值的不同表示的問題,因此提供這種“轉換”的 IO 流:
#include <sstream>
#include <iostream>
int main() {
std::stringstream ss{"0x42"};
int x = 0;
ss >> std::hex >> x;
std::cout << x << "\n";
std::cout << std::hex << x;
}
輸出:
66
42
uj5u.com熱心網友回復:
像這樣:
#include <string>
#include <iostream>
int main()
{
std::string s = "0x42";
int i = std::stoi( s, nullptr, 16 );
int j = strtoul( s.substr(2).c_str(), nullptr, 16 );
std::cout << i << "," << j << "\n";
}
請注意,std::stoi它將處理前導“0x”。 strtoul更挑剔。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/410758.html
標籤:
上一篇:根據長度從串列中洗掉字串?
下一篇:提取多個字串的相同開頭部分
