【问题标题】:How to convert char to int, and vice versa?如何将char转换为int,反之亦然?
【发布时间】:2021-06-10 12:06:19
【问题描述】:

我想在不使用输出格式的情况下将char 转换为int,反之亦然。我该怎么做?

【问题讨论】:

  • (int)c 效果很好。 c - '0' 也可以。请详细说明您的问题。举例说明预期的输入和输出。
  • 只需转换变量。字符 c;诠释 i = 25; c= (char) i;
  • my_char = '10' my_int = int(my_var); my_str = str(my_int) ;如果它不能转换 python raise ValueError

标签: c char type-conversion integer


【解决方案1】:

你说的是一个单个位字符,比如'1''9'?然后你会做这样的事情:

char c = '5';      
int  x = c - '0';  // x == 5

数字编码在所有字符字符编码方案(ASCII、EBCDIC 等)中都是连续的,因此减去 '0' 的代码可以得到正确的值。

您是在说将字符编码转换为整数吗?然后您需要做的就是将字符值分配给int

int x = '5'; // x contains the character encoding of '5' - in ASCII, 53

您是在谈论转换字符字符串,例如"12""42"?然后您需要使用sscanfstrtolatoi 库函数之一(或滚动您自己的等效函数)。给定

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

【讨论】:

    【解决方案2】:

    如果要打印字符的 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)
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 2021-01-01
      • 1970-01-01
      相关资源
      最近更新 更多