问题
I'm just wondering if following is the right way to convert int to display it as a char
#include <stdio.h>
int main()
{
int x = 500;
printf("%hhd\n", x);
}
Also, from above I wonder if I should do the following to display the value of character.
#include <stdio.h>
int main()
{
char c = 'a';
printf("%hhd\n", c);
}
Or would just printf("%d\n", c);
be fine? So, basically I'm trying to output the first byte of integer through printf without any casting.
回答1:
Using %hhd
in your first example forces a C99-compliant printf()
to convert the int
it is passed to a char
before printing it. Depending on whether your characters are signed or unsigned, you might see 244 or -12 as the value printed. It is debatable whether this is the 'correct' way to print it; most probably not. The normal way to print a character is with %c
. One issue is what is 500
supposed to represent as a character; its value is out of range (on almost all platforms) for char
, signed char
or unsigned char
types. If it is a Unicode character or other wide character value, then you probably need to use the wide-character formatting variant — wprintf()
.
Your second example using %c
format and a plain char
value 'a'
is well behaved and conventional. That will print the letter 'a'. If you use %hhd
, it will also work and will usually print 97 (you'd have to be on an unusual computer to get a different value).
回答2:
#include <stdio.h>
int main()
{
int x = 500;
printf("%hhu\n", x);
}
this will print 244
.
500 = 00000001 11110100
244 = 11110100
来源:https://stackoverflow.com/questions/13595628/converting-an-int-to-char-using-printf