[英]How to convert int to char/string and vice versa in linux(gcc)?
[英]How to convert char to int, and vice versa?
我想在不使用 output 格式的情況下將char
轉換為int
,反之亦然。 我怎么做?
您是在談論單個數字字符,例如'1'
或'9'
嗎? 然后你會做這樣的事情:
char c = '5';
int x = c - '0'; // x == 5
數字編碼在所有字符字符編碼方案(ASCII、EBCDIC 等)中都是連續的,因此減去'0'
的代碼可以得到正確的值。
您是在談論將字符編碼轉換為 integer 嗎? 然后您需要做的就是將字符值分配給int
:
int x = '5'; // x contains the character encoding of '5' - in ASCII, 53
您是在談論轉換字符串,例如"12"
或"42"
嗎? 然后您需要使用sscanf
、 strtol
或atoi
庫函數之一(或滾動您自己的等效函數)。 給定
char str[] = "123";
int x;
你會做的
sscanf( str, "%d", &x );
或者
x = atoi( str );
或者
char *chk;
x = (int) strtol( str, &chk, 10 );
if ( !isspace( *chk ) && *chk != 0 )
// str contained a non-numeric character, handle as appropriate
如果要打印字符的 ASCII 值
char c1 = 'A';
printf("%d",(int)c1); //Prints ASCII value of character 'A' = (65)
以下代碼還打印字符的 ASCII 值
char c1 = 'A';
printf("%d ",c1); //Prints ASCII value of character 'A' = (65)
如果要打印字符的值
char c2 = '5';
int x = c2-'0';
printf("%d",x); //prints integer value of character '5'(5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.