I know that ctype.h defines isdigit, however this only works for base 10. I’d like to check to see if a number is a digit in a given base int b.
What’s the best way to do this in C?
Edit
I’ve come up with the following function:
int y_isdigit(char c, int b) {
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int digitslen = sizeof digits - 1;
static int lowest = 0;
int highest = b - 1;
if(highest >= digitslen)
return -1; /* can't handle bases above 35 */
if(b < 1)
return -2; /* can't handle bases below unary */
if(b == 1)
return c == '1'; /* special case */
int loc = strchr(digits, c);
return loc >= lowest && loc <= highest;
}
Is there any advantage to using the version schnaader made to this? (This seems to have the added benefit of not relying on the user’s charset being ASCII—not that it matters much anymore.)
I’d suggest something like this:
This should work (untested) for base 2..36 if you’re using
0..9andA..Z.An alternative would be to use a boolean lookup table, this is the fastest way to check. For example you could prepare tables for bases 2..36, using up 256*35 = 8960 bytes of memory, after this the
isdigitcheck is a simple memory read.