Convert char to int in C#

后端 未结 14 809
情深已故
情深已故 2020-11-22 10:44

I have a char in c#:

char foo = \'2\';

Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value o

相关标签:
14条回答
  • 2020-11-22 11:11
    char c = '1';
    int i = (int)(c-'0');
    

    and you can create a static method out of it:

    static int ToInt(this char c)
    {
        return (int)(c - '0');
    }
    
    0 讨论(0)
  • 2020-11-22 11:11

    Comparison of some of the methods based on the result when the character is not an ASCII digit:

    char c1 = (char)('0' - 1), c2 = (char)('9' + 1); 
    
    Debug.Print($"{c1 & 15}, {c2 & 15}");                                   // 15, 10
    Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}");                                 // 31, 10
    Debug.Print($"{c1 - '0'}, {c2 - '0'}");                                 // -1, 10
    Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}");                     // 4294967295, 10
    Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1
    
    0 讨论(0)
  • 2020-11-22 11:14

    Interesting answers but the docs say differently:

    Use the GetNumericValue methods to convert a Char object that represents a number to a numeric value type. Use Parse and TryParse to convert a character in a string into a Char object. Use ToString to convert a Char object to a String object.

    http://msdn.microsoft.com/en-us/library/system.char.aspx

    0 讨论(0)
  • 2020-11-22 11:14

    This worked for me:

    int bar = int.Parse("" + foo);
    
    0 讨论(0)
  • 2020-11-22 11:20

    Principle:

    char foo = '2';
    int bar = foo & 15;
    

    The binary of the ASCII charecters 0-9 is:

    0   -   0011 0000
    1   -   0011 0001
    2   -   0011 0010
    3   -   0011 0011
    4   -   0011 0100
    5   -   0011 0101
    6   -   0011 0110
    7   -   0011 0111
    8   -   0011 1000
    9   -   0011 1001
    

    and if you take in each one of them the first 4 LSB (using bitwise AND with 8'b00001111 that equals to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )

    Usage:

    public static int CharToInt(char c)
    {
        return 0b0000_1111 & (byte) c;
    }
    
    0 讨论(0)
  • 2020-11-22 11:21

    I'm using Compact Framework 3.5, and not has a "char.Parse" method. I think is not bad to use the Convert class. (See CLR via C#, Jeffrey Richter)

    char letterA = Convert.ToChar(65);
    Console.WriteLine(letterA);
    letterA = 'あ';
    ushort valueA = Convert.ToUInt16(letterA);
    Console.WriteLine(valueA);
    char japaneseA = Convert.ToChar(valueA);
    Console.WriteLine(japaneseA);
    

    Works with ASCII char or Unicode char

    0 讨论(0)
提交回复
热议问题