C++で文字をASCIIに変換する
この投稿では、C++でcharをASCIIコードに変換する方法について説明します。
C++でcharをASCIIコードに変換する簡単な解決策は、型キャストを使用することです。その使用例を次に示します。
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = int(c); std::cout << i << std::endl; // 75 return 0; } |
または、charをintに割り当てることにより、charをASCIIコードに暗黙的に変換することもできます。 charはすでに数値であるため、これは機能します。
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = c; std::cout << i << std::endl; // 75 return 0; } |
C++は4種類のタイプも提供します キャスティングオペレーター – static_cast
, dynamic_cast
, reinterpret_cast
、 と const_cast
。変換を安全かつ明示的にするために、使用を検討してください static_cast
.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = static_cast<int>(c); std::cout << i << std::endl; // 75 return 0; } |
これで、C++でcharをASCIIコードに変換できます。
こちらも参照: