Reputation: 97
In the below program
#include<stdio.h>
int main()
{
int k=65;
printf(" The ASCII value is : %c",k);
return 0;
}
The output is "The ASCII Value is : A" . I just don't understand how does %c brought the corresponding ASCII value of that number? I mean how does an integer value is referred to %c(instead of %d) and still brought the ASCII value? How does this process work? Please explain.
Upvotes: 1
Views: 198
Reputation: 97
I think the following answer helps you. Credits to Sujeet Gholap.
the %c works as following: 1. Take the least significant byte of the variable 2. Interpret that byte as an ascii character
that's it
so, when you look at the four bytes of 65, (in hex), they look like
00 00 00 41
the %c looks at the 41
and prints it as A
that's it
#include<stdio.h>
int main()
{
int k=65 + 256;
printf(" The ASCII value is : %c",k);
return 0;
}
consider that code
where k is
00 00 01 41
here, even now, the last byte is 41
so, it still prints A
Upvotes: 0
Reputation: 141628
The short version: your operating system has a table that links a graphical symbol to each integer , and for 65 it has linked the graphics for "A". The ASCII standard says that 65 should be linked to a graphic that humans can read as "A".
Upvotes: 0
Reputation: 69954
Its not the "%c" that is doing it. When you run your program, all it does is outputs a sequence of bytes (numbers) to the standard output. If you use "%c" it will output a single byte of value 65 and if you use "%d" it will output two bytes, one with value 54 for the 6 and with value 53 for the 5. Then, your terminal displays those bytes as character glyphs, according to what encoding it is using. If your terminal is using an ascii-compatible encoding then 65 will be the code for "A".
Upvotes: 3