Convert char to int in C and C++

前端 未结 12 2146
梦毁少年i
梦毁少年i 2020-11-22 02:41

How do I convert a char to an int in C and C++?

12条回答
  •  眼角桃花
    2020-11-22 03:08

    char is just a 1 byte integer. There is nothing magic with the char type! Just as you can assign a short to an int, or an int to a long, you can assign a char to an int.

    Yes, the name of the primitive data type happens to be "char", which insinuates that it should only contain characters. But in reality, "char" is just a poor name choise to confuse everyone who tries to learn the language. A better name for it is int8_t, and you can use that name instead, if your compiler follows the latest C standard.

    Though of course you should use the char type when doing string handling, because the index of the classic ASCII table fits in 1 byte. You could however do string handling with regular ints as well, although there is no practical reason in the real world why you would ever want to do that. For example, the following code will work perfectly:

      int str[] = {'h', 'e', 'l', 'l', 'o', '\0' };
    
      for(i=0; i<6; i++)
      {
        printf("%c", str[i]);
      }
    

    You have to realize that characters and strings are just numbers, like everything else in the computer. When you write 'a' in the source code, it is pre-processed into the number 97, which is an integer constant.

    So if you write an expression like

    char ch = '5';
    ch = ch - '0';
    

    this is actually equivalent to

    char ch = (int)53;
    ch = ch - (int)48;
    

    which is then going through the C language integer promotions

    ch = (int)ch - (int)48;
    

    and then truncated to a char to fit the result type

    ch = (char)( (int)ch - (int)48 );
    

    There's a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.

提交回复
热议问题