I\'ve seen examples of this all over the place:
int i = 2;
char c = i + \'0\';
string s;
s += char(i + \'0\');
However, I have not yet seen
The C++ standard says, in its [lex.charset] section “the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous” (quoted from draft N4659).
Thus, the value of '1'
is '0'+1
, and the value of '2'
is one more than that, which is '0'+2
, and so on. If n
has a value from 0 to 9, then '0'+n
is the value for the corresponding character from '0'
to '9'
.
(Unlike the earlier answers, this answer does not assume ASCII and shows how the property derives from the C++ standard.)
(char)(i+c)
where c
is a char
gives you a new char
with an ascii value equal to (ascii value of c
) + i
. Since the ascii values of the digits 0-9 are sequential, i+'0'
gives you the char corresponding to i
, as long as i
lies in the appropriate range.
EDIT : (i+c)
is an int, as Jarod42 pointed out. Added a cast to maintain correctness.
When ASCII encoding is used, the integer value of '0'
is 48
.
'0' + 1 = 49 = '1'
'0' + 2 = 50 = '2'
...
'0' + 9 = 57 = '9'
So, if you wanted convert a digit to its corresponding character, just add '0'
to it.
Even if the platfrom uses non-ASCII encoding, the lanuage still guarantees that the characters '0'
- '9'
must be encoded such that:
'1' - '0' = 1
'2' - '0' = 2
'3' - '0' = 3
'4' - '0' = 4
'5' - '0' = 5
'6' - '0' = 6
'7' - '0' = 7
'8' - '0' = 8
'9' - '0' = 9
When ASCII encoding is used, that becomes:
'1' - '0' = 49 - 48 = 1
'2' - '0' = 50 - 48 = 2
'3' - '0' = 51 - 48 = 3
'4' - '0' = 52 - 48 = 4
'5' - '0' = 53 - 48 = 5
'6' - '0' = 54 - 48 = 6
'7' - '0' = 55 - 48 = 7
'8' - '0' = 56 - 48 = 8
'9' - '0' = 57 - 48 = 9
Hence, regardless of the character encoding used by a platform, the lines
int i = 2;
char c = i + '0';
will always result in the value of c
being equal to the character '2'
.
It's based on ASCII values. Adding the ASCII value of 0 which is 48 means that 48 + 5 will be 53 or ASCII 53 which is 5.
Google ASCII and find a good chart and study it. It should make sense once you look at the values for each char (character).
A char will convert the integer to corresponding value based on ASCII value, So if you assign a value of 48 to a char it will store 0 since,48 is the ASCII value of 0.Correspondingly you add the ASCII value of 0 to any integer you need to convert to char
If you look at the ASCII table, asciitable, you'll see that the digits start at 48 (being '0') and go up to 57 (for '9'). So in order to get the character code for a digit, you can add that digit to the character code of '0'.