With the following code:
#include <stdio.h>
int main(void) {
printf("%c %c ", 82, 2130);
return 0;
}
I'm getting the output:
R R
How 2130 is converted to R?
With the following code:
#include <stdio.h>
int main(void) {
printf("%c %c ", 82, 2130);
return 0;
}
I'm getting the output:
R R
How 2130 is converted to R?
The way printf processes the c conversion specifier is given in C 2018 (the 2018 edition of the ISO/IEC C standard) 7.21.6.1 8, which says:
… If no
llength modifier is present, theintargument is converted to anunsigned char, and the resulting character is written.
Thus, 2130 is converted to an unsigned char. The rules for this conversion are given in 6.3.1.3. In a typical C implementation, unsigned char has eight bits and can represent values from 0 to 255. In this case, paragraph 2 applies:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
This complicated sentence says the value is reduced modulo 256: “one more than the maximum value that can be represented in the new type” is one more than 255, which is 256. So 2130 is reduced by subtracting 256 repeatedly until the result is in the range 0 to 255. Subtracting 256 eight times yields 2130 − 8•256 = 82.
Then the character with code 82 is printed. The C standard does not specify what code is used for characters, but it is common for modern C implementations to use ASCII. In ASCII, 82 is the code for “R”.
Since the title of the question asks about converting to a char, I will point out that char may be signed or unsigned. If it is unsigned, the conversion is as described above. If it is signed and the source value cannot be represented in char, the conversion is covered by 6.3.1.3 3, which says the result is implementation-defined or an implementation-defined signal is raised. However, there is no conversion to char in the code in the question, as printf is specified to convert to unsigned char.
ASCII based int to char conversion gets only last 2 digits of reduced hex value. So you see just R.