C语言 c语言如何将十进制值转换为字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18330970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert decimal value to character in c language
提问by Ши?аковски Глигор
I have an array of char but values is decimal representation of a character. example:
我有一个字符数组,但值是字符的十进制表示。例子:
char bytes[4]={50,48,49,51}
how to convert this to get char array like this:
如何将其转换为这样的字符数组:
char bytes1[4]={2,0,1,3}
回答by DrYap
When you create your array you should use character literals:
创建数组时,应使用字符文字:
char bytes[4] = {'2', '0', '1', '3'};
These are stored in memory in the character encoding your compiler is using which converts the character to a number.
它们以编译器使用的字符编码存储在内存中,将字符转换为数字。
If you want to get the decimal value represented by the character when read by a human (i.e. '2' -> 2) then you can do bytes[x] - '0'assuming the digit characters are adjacent in the character encoding (which is true of ASCII and UTFs at least).
如果您想在人类读取时获得由字符表示的十进制值(即 '2' -> 2),那么您可以bytes[x] - '0'假设数字字符在字符编码中是相邻的(至少对于 ASCII 和 UTF 是这样) )。
回答by Sandeep Singh
The Input Array for this Question is:
这个问题的输入数组是:
char bytes[4]={50,48,49,51}
In the Memory, the characters are stored as corresponding ASCIIvalues (or any other character encoding scheme, chosen by your compiler): http://en.wikipedia.org/wiki/ASCII
在内存中,字符存储为相应的ASCII值(或任何其他字符编码方案,由您的编译器选择):http: //en.wikipedia.org/wiki/ASCII
For the given input, the ASCIIValue - Char Mapping is as follows:
对于给定的输入,ASCII值 - 字符映射如下:
ASCII Value || Character
48 || '0'
49 || '1'
50 || '2'
51 || '3'
Note:
笔记:
A. To Convert a Given Character Value to the Corresponding Integer Value:
A. 将给定的字符值转换为相应的整数值:
Subtract '0'.
Example: '2' - '0' = (int) 2
B. To Convert a Given Integer Value to the Corresponding Character:
B. 将给定的整数值转换为相应的字符:
Add '0'.
Example: 2 + '0' = 50 {ASCII Value for '2'}
Print the Character Values for the Given Input Array:
打印给定输入数组的字符值:
int main ()
{
char bytes[4]={50,48,49,51};
int i=0;
/* Print The Equivalent Character Values */
for (i=0; i<4; i++)
{
printf ("%c\t", bytes[i]);
}
return 0;
}
Output:
输出:
2 0 1 3
回答by No Idea For Name
if you have an array of chars and want to get their values as integers you can do
如果您有一个字符数组并希望将它们的值作为整数获取,您可以这样做
int a = bytes[0] - '0';

