如何将char转换为int?

tvr*_*tvr 122 .net c#

什么是一个转换的正确方法charint?这给出了49:

int val = Convert.ToInt32('1');
//int val = Int32.Parse("1"); // Works
Run Code Online (Sandbox Code Playgroud)

我不想转换为字符串,然后解析它.

Joe*_*ler 277

我很惊讶没人提到内置的静态方法System.Char......

int val = (int)Char.GetNumericValue('8');
// val == 8
Run Code Online (Sandbox Code Playgroud)

  • 有许多Unicode字符表示非整数,例如[U + 2153](http://www.fileformat.info/info/unicode/char/2153/index.htm). (48认同)
  • @dtb - 我没有考虑过.`Char.GetNumericValue('⅓')`确实返回`0.3333 ......`.感谢您指出了这一点! (25认同)
  • 好点!+1非常奇怪它返回一个`double`,但是 (18认同)
  • 我同意,我无法弄清楚为什么它返回'double' - 单个字符怎么可能代表一个浮点数呢? (4认同)

Mar*_*ell 40

如何(为char c)

int i = (int)(c - '0');
Run Code Online (Sandbox Code Playgroud)

哪个减少了char值?

重新提出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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用 int x = c.ParseInt32();

  • 如果你想要一个类似于`int.Parse`的行为,即在无效输入上抛出异常,你需要添加额外的边界检查:`if(i <0 || i> 9)抛出新的FormatException();` (4认同)

Ste*_*vds 21

每个人都在伪造的是解释为什么会发生这种情况.

Char,基本上是一个整数,但在ASCII表中有一个指针.所有字符都有一个相应的整数值,您可以在尝试解析时清楚地看到它.

Pranay显然有不同的字符集,这就是为什么HIS代码不起作用.唯一的方法是

int val = '1' - '0';
Run Code Online (Sandbox Code Playgroud)

因为这会查找表中的整数值,'0'然后"基值"从中减去char格式的数字,这将为您提供原始数字.


Gri*_*rif 15

int i = (int)char.GetNumericValue(c);
Run Code Online (Sandbox Code Playgroud)

还有一个选择:

int i = c & 0x0f;
Run Code Online (Sandbox Code Playgroud)

这也应该做到这一点.