lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[cpp]:  【字符】和【ascii值】之间的转换

 

 

 

 

一、基础:

 

  1、将【字符】转化为【ascii值】(   char -> int  ):

1     char c = '-' ;
2     
3     //  char -> int
4     int c_out = int(c) ;

 

  2、将【ascii值】转化为【字符】(  int -> char  ):

1     int  ic = 45 ;
2 
3     //  int -> char
4     char out_ic = char(ic) ;

 

 

二、代码

 1 #include <iostream>
 2 
 3 using namespace std ;
 4 
 5 void run()
 6 {
 7     char c = '?' ;
 8     
 9     //  char -> int
10     int c_out = int(c) ;
11 
12     
13     int  ic = 63 ;
14 
15     //  int -> char
16     char out_ic = char(ic) ;
17 
18     
19     cout << c << " --> " << c_out << endl ;
20     cout << ic << " --> " << out_ic << endl ;
21 }
22 
23 int main()
24 {
25     run() ;
26     
27     return 0 ;
28 }

 

 

 

 

三、输出

1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2 
3 
4 ? --> 63
5 63 --> ?

 

 

 

 

四、参考文档

 

  1、  C++程序 打印字符的ASCII值  --  https://deepinout.com/cpp/cpp-examples/g_cpp-program-to-print-ascii-value-of-a-character.html

 

posted on 2024-01-25 03:27  lnlidawei  阅读(56)  评论(0编辑  收藏  举报