Converting an int to char using printf

帅比萌擦擦* 提交于 2019-12-02 17:28:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!