views:

1195

answers:

3
Character.digit(char ch, int radix)

Returns the numeric value of the character ch in the specified radix.

Is there an equivalent function in c#?

+1  A: 

No, as of version 3.5, there's no equivalent in the .NET Framework BCL. It's pretty easy to write though.

static int GetIntegerValue(char c, int radix)
{
    int val = -1;
    if (char.IsDigit(c))
        val = (int)(c - '0');
    else if (char.IsLower(c))
        val = (int)(c - 'a') + 10;
    else if (char.IsUpper(c))
        val = (int)(c - 'A') + 10;
    if (val >= radix)
        val = -1;
    return val;
}
Mehrdad Afshari
Btw, this fails for characters beside 0..9, a-z, A-Z (international digits/letters).
Mehrdad Afshari
This is how you'd do it in C, yes. For languages like C# and Java, when you write this kind of code you have to stop and ask yourself "why am I reinventing the wheel?". Using Convert.ToInt32(string s, int fromBase) is the correct way to do this.
Avish
Avish: The "correct" way depends on the context you'd want to use it. If you're only dealing with English chars and you've a large data set, this will probably beat Convert.ToInt32 performance wise.
Mehrdad Afshari
+4  A: 

I don't know of a direct equivalent
The closest match I can find is

Convert.ToInt32(string s, int baseFrom);

So you could convert your char to string then pass it in to the above function to get the int32 or Int16 or Byte or however you want to handle it :

char c = 'F';

int digit = Convert.ToInt32(c.ToString(),16);

Note - Convert will throw a FormatException if the char isn't a digit

zebrabox
A: 
bool isDigit = char.IsDigit('a');

This only does numbers 0-9 however, so for hex you would have to add code to see if your char was between a and f.

char.IsNumber will handle more numeric characters but may not be what you want.

See this post for making an extension method to handle this for you: http://stackoverflow.com/questions/228523/char-ishex-in-c

John JJ Curtis