C++で16進文字列を整数に変換します
この投稿では、C++で16進文字列を整数に変換する方法について説明します。
1.文字列ストリームの使用
いつ basefield
フォーマットフラグはに設定されます hex
文字列ストリームの場合、ストリームに挿入される整数値は基数16で表されます。これは、 std::hex
マニピュレータ、次のように:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "3e8"; unsigned int i; std::istringstream iss(s); iss >> std::hex >> i; std::cout << i << std::endl; // 1000 return 0; } |
2.使用する std::stoul
別のオプションは、 std::stoul
16進文字列を指定された基数の符号なし整数に変換するための関数。 The stoul
関数はC++11で導入され、ヘッダーで定義されています <string>
と使用 std::strtoul
変換を実行します。も参照してください std::stoi
, std::stol
、 と std::stoull
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "3e8"; unsigned int i = std::stoul(s, nullptr, 16); std::cout << i << std::endl; // 1000 return 0; } |
The std::stoul
関数がスローします std::invalid_argument
不正な入力の例外と std::out_of_range
整数のオーバーフローで。ご了承ください std::stoul
次のような文字列を変換します 3e8x
整数に 1000
(16進 3e8
)そして例外をスローしません。
3.使用する boost::lexical_cast
Boost C++ライブラリをすでに使用している場合は、16進文字列を次の整数に変換できます。 boost::lexical_cast<int>、以下に示すように。に注意してください boost::lexical_cast
舞台裏で文字列ストリームを使用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <boost/lexical_cast.hpp> int main() { std::string s = "3e8"; try { unsigned int i = boost::lexical_cast<int>(s); std::cout << i << std::endl; // 1000 } catch(boost::bad_lexical_cast &e) { //入力が正しくありません-例外を処理します } return 0; } |
4.使用する sscanf
最後に、 sscanf()
フォーマット文字列を使用して16進C文字列を整数に変換する関数 %x
。あなたはそれを動作させるために以下のようなことをすることができます std::string
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string s = "3e8"; int i; sscanf(s.c_str(), "%x", &i); std::cout << i << std::endl; // 1000 return 0; } |
これで、C++で16進文字列を整数に変換することができます。