2

Possible Duplicate:
How to convert a single char into an int

I am working on a program that requires an integer be pulled from a string, and then added to other integers.

I.E. Input "123456789". I can pull out the 5th char, '5', but I need to add this to another int. If I try to convert this to int, it returns the ASCI value. Is there any way to convert a char to its corresponding int?

Community
  • 1
  • 1
user1486548
  • 1,201
  • 4
  • 15
  • 22

1 Answers1

9

Just subtract away the ASCII value of character '0'.

e.g. '5' - '0' = 5

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 3
    Note that that also works in EBCDIC :) – Daniel Fischer Jul 05 '12 at 18:27
  • @DanielFischer: Thank so much for your comment. What will happen if using ASCII? – Jack Jul 05 '12 at 18:57
  • 1
    @Jack It will work too. Daniel noted that because some similar tricks (for example, `'f'-'a'==5`) don't work in EBCDIC. – asaelr Jul 05 '12 at 19:06
  • 1
    @asaelr That one in particular does work in EBCDIC, the splits are between 'i' and 'j' and between 'r' and 's' (yeah, I had to look it up, why do you ask?). – Daniel Fischer Jul 05 '12 at 19:16
  • 1
    Thanks. (I talked about the general case, and did not look up :) ,also, for some reason, I thought that there are more splits.) – asaelr Jul 05 '12 at 23:59