如何将整数转换为C中的字符? [英] How to convert integers to characters in C?

查看:124
本文介绍了如何将整数转换为C中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果整数为97,则字符为'a',或98为'b'。

For example, if the integer was 97, the character would be 'a', or 98 to 'b'.

推荐答案

在C中, int char long

它们通常有不同的内存大小,因此不同的范围,如 INT_MIN INT_MAX char 和数组 char 通常用于存储字符和字符串。整数以许多类型存储: int 是速度,大小和范围的平衡最受欢迎的。

They typically have different memory sizes and thus different ranges as in INT_MIN to INT_MAX. char and arrays of char are often used to store characters and strings. Integers are stored in many types: int being the most popular for a balance of speed, size and range.

ASCII是迄今为止最流行的字符编码,但其他存在。 'A'的ASCII码为65,'a'为97,'\\\
'为10等等。ASCII数据最常存储在 char 变量。如果C环境使用ASCII编码,以下都将相同的值存储到整数变量中。

ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.

int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;

要将 int 转换为 char ,简单赋值:

To convert an int to a char, simple assign:

int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4; 

此警告出现,因为 int char 的范围更大,因此可能会发生一些信息丢失。通过使用转换(char),可能会丢失信息。

This warning comes up because int typically has a greater range than char and so some loss-of-information may occur. By using the cast (char), the potential loss of info is explicitly directed.

整数:

printf("<%c>\n", c3); // prints <b>

// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>

// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>

printf("<%d>\n", i3); // prints <98>

有关于打印的其他问题,例如使用%hhu 或在打印 unsigned char 时进行投射,但请稍后重试。有很多要 printf()

There are additional issues about printing such as using %hhu or casting when printing an unsigned char, but leave that for later. There is a lot to printf().

这篇关于如何将整数转换为C中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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