如何以正确的方式将 char
转换为 int
? 这会返回 49
:
int val = Convert.ToInt32('1');
//int val = Int32.Parse("1"); // Works
我不想将其转换为字符串,然后再解析。
我很惊讶没有人提到静态方法直接内置在 System.Char
中...
int val = (int)Char.GetNumericValue('8');
// val == 8
char c怎么样呢?
int i = (int)(c - '0');
哪种方法可以对字符值进行减法操作?
关于API的问题(评论),也许可以使用扩展方法?
public static class CharExtensions {
public static int ParseInt32(this char value) {
int i = (int)(value - '0');
if (i < 0 || i > 9) throw new ArgumentOutOfRangeException("value");
return i;
}
}
然后使用 int x = c.ParseInt32();
int.Parse
的行为,即在无效输入时抛出异常,那么你需要添加额外的边界检查:if (i < 0 || i > 9) throw new FormatException();
。 - Dirk Vollmar(int)Char.GetNumericValue(ch);
还是 (int)(c - '0');
还是 c & 0x0f
(可能更快)? - Jack大家都忽略了解释为什么会发生这种情况。
Char基本上是一个整数,但它指向ASCII表中的一个指针。所有字符都有相应的整数值,当您尝试解析它时,可以清楚地看到这一点。
Pranay显然有不同的字符集,这就是他的代码不起作用的原因。唯一的方法是
int val = '1' - '0';
因为这个过程在表格 '0'
中查找整数值,然后得到了“基准值”,从该值中减去以字符格式表示的数字即可得到原始数字。
int i = (int)char.GetNumericValue(c);
另一种选择:
int i = c & 0x0f;
这也应该可以实现。
int val = '1' - '0';
这可以使用ASCII码来完成,其中'0'是最低的数字字符,其余数字字符依次递增。
int val = '1' - 48;
You may use the following extension method:
public static class CharExtensions
{
public static int CharToInt(this char c)
{
if (c < '0' || c > '9')
throw new ArgumentException("The character should be a number", "c");
return c - '0';
}
}
char
转换为 int
,我们必须检查输入参数的范围,而不是输出的 int
值的范围。 - Eugene Cheverdaint
值,因为在方法开始时已经执行了数字字符范围检查,所以如果指定的字符不在数字字符范围内,将抛出异常并得到正确的结果值。与您提供的逻辑相同,但是在方法开始时执行了范围检查。 - Eugene Cheverdaif (c < 0 || c > 9)
... - Dirk Vollmarint val = '1' & 15;
ASCII字符0-9的二进制为:
0 - 00110000
1 - 00110001
2 - 00110010
3 - 00110011
4 - 00110100
5 - 00110101
6 - 00110110
7 - 00110111
8 - 00111000
9 - 00111001
如果你取每个数字的前4位LSB(使用与8'b00001111的按位AND运算,等于15),你就得到了实际的数字(0000 = 0,0001 = 1,0010 = 2,...)
最安全的方法是使用Int32.TryParse方法。请参见此处: http://dotnetperls.com/int-tryparse
在其他答案的基础上进行扩展,涉及十六进制表示:
public int CharToInt(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'a' && c <= 'f')
{
return 10 + c - 'a';
}
else if (c >= 'A' && c <= 'F')
{
return 10 + c - 'A';
}
return -1;
}
Char.GetNumericValue('⅓')
确实会返回0.3333...
。感谢您指出这一点! - Joel Mueller