如何在C和c++中将字符转换为int ?
当前回答
我建议使用以下函数:
/* chartoint: convert char simbols to unsigned int*/
int chartoint(char s[])
{
int i, n;
n = 0;
for (i = 0; isdigit(s[i]); ++i){
n = 10 * n + (s[i] - '0');
}
return n;
}
函数的结果可以通过以下方法检查:
printf("char 00: %d \r\n", chartoint("00"));
printf("char 01: %d \r\n", chartoint("01"));
printf("char 255: %d \r\n", chartoint("255"));
其他回答
嗯,在ASCII码中,数字(数字)从48开始。你所需要做的就是:
int x = (int)character - 48;
或者,因为字符'0'的ASCII码是48,你可以这样写:
int x = character - '0'; // The (int) cast is not necessary.
这取决于你想做什么:
如果要以ASCII码的形式读取该值,可以写入
char a = 'a';
int ia = (int)a;
/* note that the int cast is not necessary -- int ia = a would suffice */
要转换字符'0' -> 0,'1' -> 1,等等,你可以写
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
解释: A - '0'等价于((int) A) - ((int)'0'),这意味着字符的ASCII值相互相减。因为在ascii表中0直接出现在1之前(以此类推,直到9),两者之间的差就给出了字符a所代表的数字。
对于char或short to int,只需要赋值。
char ch = 16;
int in = ch;
与int64相同。
long long lo = ch;
所有值都是16。
使用static_cast < int >:
int num = static_cast<int>(letter); // if letter='a', num=97
编辑:你可能应该尽量避免使用(int)
Int num = (Int)字母;
为什么使用static_cast<int>(x)而不是(int)x?更多信息。
C和c++总是将类型提升到至少int。此外,字符字面量在C中是int类型,在c++中是char类型。
可以通过赋值给int类型来转换char类型。
char c = 'a'; // narrowing on C
int a = c;
推荐文章
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- 使用C返回一个数组
- Printf与std::字符串?
- 禁用复制构造函数
- 只接受特定类型的c++模板
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 为什么pthreads的条件变量函数需要互斥?
- c++ 11中的递归lambda函数
- 如何在构建目标之外生成gcc调试符号?
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- __FILE__宏显示完整路径
- 就性能而言,使用std::memcpy()还是std::copy()更好?
- 为什么布尔值是1字节而不是1位?