Convert char to int in C#

后端 未结 14 1062
情深已故
情深已故 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: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;
    }
    

提交回复
热议问题