Detail the char data type in C and its conversion to int

  • 2020-04-02 03:13:56
  • OfStack

Char variable in C

Char is one of the odder types of C/C++ integer data. Others, such as int/long/short, are signed by default if they do not specify signed/unsigned. While char is unsigned in the standard (because the char type was originally proposed to refer to ASCII, which ranges from 0 to 127), whether it is actually signed or unsigned depends on the compiler.
The compiler's default char type can be determined by the following procedure:


void char_type()
{
 char c=0xFF;
 if(c==-1)
  printf("signed");
 elseif(c==255)
  printf("unsigned");
 else
  printf("error!");
}

When you are unsure of the compiler's default char type, use display declarations: signed char and unsigned char;

In C/C++ language, char variable is a byte, 8 bits, signed char range: -128~127 [-128 in memory binary is 1000 0000000, 127 in memory is 0111 1111]; Unsign char range: 0000 0000~1111 1111, i.e. 0~255;

Note: the integer in memory is complementary access, positive complement: equal to itself, negative complement: take the inverse plus 1, such as: 127 in memory as 0111 1111, -127 in memory as ~(0111 1111)+1=1000 0001; Suppose that the contents of a memory unit p are 1111 1111, then must it be 255? It really depends on whether your code wants to view it as a signed or unsigned number, 255 if it's unsigned, -1 if it's signed:


signed char c=*p; //c=-1
unsigned char c=*p;//c=255

This also explains that the code above determines the compiler's default char type.

Char to int
Conversion method


 a[i] - '0' 


The reference program


 #include <stdio.h> 
 #include <stdlib.h> 
 #include <string.h> 
  
 int main() 
 { 
  char str[10]; 
  int i, len; 
  
  while(scanf("%s", str) != EOF) 
  { 
   for(i = 0, len = strlen(str); i < len; i++) 
   { 
    printf("%d", str[i] - '0'); 
   } 
   printf("n"); 
  } 
  
  return 0; 
 } 


Int is converted to char

Conversion method


 a[i] + '0' 


The reference program

 


 #include <stdio.h> 
 #include <stdlib.h> 
 #include <string.h> 
  
 int main() 
 { 
  int number, i; 
  char str[10]; 
  
  while(scanf("%d", &number) != EOF) 
  { 
   memset(str, 0, sizeof(str)); 
   
   i = 0; 
   while(number) 
   { 
    str[i ++] = number % 10 + '0'; 
    number /= 10; 
   }   
   puts(str);  
  } 
  
  return 0; 
 } 


Related articles: