使用printf将int转换为char [英] Converting an int to char using printf

查看:151
本文介绍了使用printf将int转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道以下是否是转换int以将其显示为字符的正确方法

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);
}

或者只是 printf(%d\ n,c); 可以吗?因此,基本上,我试图通过printf输出整数的第一个字节,而不进行任何强制转换。

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.

推荐答案

使用<$ c $第一个示例中的c>%hhd 强制兼容C99的 printf()转换 int 会在打印之前传递给 char 。根据您的字符是带符号的还是无符号的,您可能会看到244或-12作为打印的值。这是否是打印的正确方法尚有争议;可能不是。打印字符的常规方法是使用%c 。一个问题是 500 应该代表什么字符?对于 char 签名的字符,其值超出范围(在几乎所有平台上) unsigned char 类型。如果它是Unicode字符或其他宽字符值,则可能需要使用宽字符格式变体- wprintf()

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().

您的第二个示例使用%c 格式和普通的 char 'a'表现良好且常规。这将打印字母 a。如果您使用%hhd ,它也将正常工作,并且通常会打印97(您必须在不寻常的计算机上才能获得不同的值)。

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).

这篇关于使用printf将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆