Converting char to int
Meta
jared771 at gmail.com
Tue Dec 31 23:27:54 PST 2013
On Wednesday, 1 January 2014 at 06:21:05 UTC, Caeadas wrote:
> I hope you'll forgive my asking an overly easy question: I've
> been searching for an answer and having trouble finding one, and
> am getting frustrated.
>
> My issue is this: I'm trying to convert character types to
> integers using to!int from std.conv, and I'm getting, for
> example, '0'->48, '1'->49, etc. It seems like there should be a
> simple way around this, but it's eluding me.
Your code is working correctly. D's chars, for all values up to
255, are the same as the ASCII character set. If you look in the
ASCII table here: http://www.asciitable.com/ you will see that
'0' corresponds to 48, and '1' corresponds to 49. The easiest
solution that will fix your code is change to!int('0') and
to!int('1') to to!int("0") and to!int("1"). It seems that for
characters the to! function just returns its ASCII value, but it
will definitely do what you want for strings. Strangely enough,
it doesn't seem like there's a function to do convert a character
to its numeric value in Phobos, but it's simple to implement.
int charToInt(char c)
{
return (c >= 48 && c <= 57) ? cast(int)(c - 48) : -1;
}
void main()
{
assert(charToInt('0') == 0);
assert(charToInt('1') == 1);
assert(charToInt('9') == 9);
assert(charToInt('/') == -1);
assert(charToInt(':') == -1);
}
More information about the Digitalmars-d-learn
mailing list