char转换为int转换 [英] Char to int conversion in C

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

问题描述

如果我想将单个数字 char 转换为数字值,例如,如果:

If I want to convert a single numeric char to it's numeric value, for example, if:

char c = '5';

,我想要 c c $ 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:


基本来源和基本执行字元集以下
成员:

[...]

十位小数位数

0 1 2 3 4 5 6 7 8 9

[...]

在源和执行基本字符集中,
在上面的十进制数字列表中的0之后的每个字符的值应该大于
的值。上一个的值。

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标准能够强加的原因。注意,字母不是连续的iN 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.

没有库函数单个 char ,您需要先构建一个字符串:

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转换为int转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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