Re: C++ way to convert ASCII digits to Integer?
blargg wrote:
blargg wrote:
andreas.koestler wrote:
On May 27, 9:18 am, "Peter Olcott" <NoS...@SeeScreen.com> wrote:
I remember that there is a clean C++ way to do this [convert
ASCII digits to Integer], but, I forgot what it was.
I don't know what you mean by 'clean C++ way' but one way to do
it is:
int ascii_digit_to_int ( const char asciidigit ) {
if ( asciidigit < '0' ||
asciidigit > '9' ) {
throw NotADigitException();
}
return (int) asciidigit - 48; // 48 => '0'
}
[...]
Not if the machine doesn't use ASCII; only a function like yours
above is fully portable.
Whoops, that's wrong too, as the above function uses '0' and '9',
which won't be ASCII on a non-ASCII machine. So the above should
really use 48 and 57 in place of those character constants, to live
up to its name. Otherwise, on a machine using ASCII, it'll work, but
on another, it'll be broken and neither convert from ASCII nor the
machine's native character set!
The requirements for numerals in the character set specify that the
values be consecutive and in increasing value.
So digit - '0' will always give you the numeric value of the numeral
the character represents, regardless of whether it is ASCII or not. The
same is not true for digit - 48.
The original problem specified conversion from ASCII, but that's not
likely what the OP really wanted. If so, then a preliminary step to
convert to ASCII could be performed, but that's probably not what was
really desired.
Brian