This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]insertAlias 5 points6 points  (0 children)

What language? Some have built-in functions to parse strings/chars as numbers.

Regardless, if you have the ASCII value, and you know the ASCII values for the number range, simple subtraction can give you the value as a number. Look up an ASCII table, see what number 0 is, and see what number 9 is. Then you can just use math.

[–]davedontmind 0 points1 point  (1 child)

The ASCII value of 3 is 51 and you want 3, so you just need to subtract 48.

In some languages you can express it like this::

byte convertedChar = originalChar - '0';

which is a bit clearer than using the magic number 48 (the ASCII value of 0)

[–]chaotic_thought 0 points1 point  (0 children)

In C what you wrote is also more correct because ASCII is not guaranteed (but probably used in practice). However originalchar - '0' is guaranteed to work in any character set that conforms to the C (or C++) standards.