CHAR在C诠释转换 [英] Char to int conversion in C
问题描述
如果我想转换一个数字字符
来它的数值,例如,如果:
If I want to convert a single numeric char
to it's numeric value, for example, if:
char c = '5';
和我想 C
持有 5
而不是'5'
,它是100%的便携式做这样吗?
and I want c
to hold 5
instead of '5'
, is it 100% portable doing it like this?
c = c - '0';
我听说所有的字符集存储在连续顺序号,所以我认为是这样,但我想知道是否有一个有组织的库函数来做到这一点的转换,以及它是如何做的常规。我是一个真正的初学者:)
I heard that all character sets store the numbers in consecutive order so I assume so, but I'd like to know if there is an organized library function to do this conversion, and how it is done conventionally. I'm a real beginner :)
推荐答案
是的,这是一个安全的转换。 C需要它的工作。这保证是部分最新的ISO C标准5.2.1条第2款,最近其中草案的 N1570 的:
Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:
这两个基本来源和基本执行字符集应具备以下
成员:结果
[...]结果
10十进制的数字的结果
0 1 2 3 4 5 6 7 8 9
结果
[...]结果
在源和执行基本字符集,该
在十进制数字上面的列表后0每个字符的值应大于1
在previous的价值。
Both the basic source and basic execution character sets shall have the following members:
[...]
the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
来自他们ASCII和EBCDIC和字符集,满足这一要求,这也是为什么C标准能够强加。需要注意的是字母的不的连续的EBCDIC和C不要求它们。
Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.
有没有库函数做了一个字符
,你需要先建立一个字符串:
There is no library function to do it for a single char
, you would need to build a string first:
int digit_to_int(char d)
{
char str[2];
str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
您也可以使用 的atoi()
函数来完成转换,一旦你有一个字符串,但 与strtol()
是更好,更安全。
You could also use the atoi()
function to do the conversion, once you have a string, but strtol()
is better and safer.
作为评论者所指出的,虽然,它是极端矫枉过正调用一个函数来做到这一点的转换;你减去最初的方法'0'是这样做的正确方法。我只是想说明如何转换一个数字作为一个字符串转换为真号的推荐标准的方法将被使用,在这里。
As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.
这篇关于CHAR在C诠释转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!