This article describes the conversion between char [character] type and int [integer] type. Since we are talking about character codes, the conversion mechanism may be the same for languages other than C.
When the int type variable is n and the char type variable is c, there are the following methods for conversion.
n+'0'//Integer → character
c-'0'//Character → integer
#include<stdio.h>
int main(void){
int n = 5;
char c = '2';
printf("%c \n", n+'0');//Integer → character
printf("%d \n", c-'0');//Character → integer
return 0;
}
5
2
You have converted it properly. Then, I will explain this mechanism.
The format specifier for the printf function, which uses the int type% d instead of the char type. As a test, take a look at the output below.
printf("%d \n", '0');
printf("%d \n", 'a');
printf("%d \n", 'A');
48
97
65
From the output, the displayed value doesn't seem to have anything to do with the original character. This is because when displayed as an int type, it is displayed in the ** character code ** of that character.
Character code | letter |
---|---|
46 | . |
47 | / |
48 | 0 |
49 | 1 |
50 | 2 |
51 | 3 |
52 | 4 |
53 | 5 |
54 | 6 |
55 | 7 |
56 | 8 |
57 | 9 |
58 | : |
59 | ; |
There are various character code conversion methods such as ASCII, UTF-8, and Shift-JIS. In most conversion methods including these, characters 0 to 9 are assigned character codes in order. That's why the output of `'0'`
is `` `48```.
Let's display the output of the previous program as a char type. The format specifier this time uses% c of char type.
printf("%c \n", 48);
printf("%c \n", 97);
printf("%c \n", 65);
0
a
A
You can see that the output result is the characters of the previous program. In other words, when the int type is displayed as the char type, the character assigned to that character code is displayed.
Now that you know the relationship between characters and character codes, you can see the mechanism of the conversion method introduced at the beginning. Since the character code is assigned in order, use this to convert the character code of 0 as a reference. In the case of int type → char type, it can be expressed by the sum with 0, and in the case of char type → int type, it can be expressed by the difference with 0.
The int and char type values must be 0 to 9 to operate normally. If you want to function the conversion, you should check that the range of values given is okay.
In C language, there is also a way to simply use 48 as the standard instead of using the character code of 0 as the standard. However, it is quite possible that the character code of 0 is not assigned as 48, and it is unnatural, so this should be stopped.
Recommended Posts