converting ascii codes to integers

hello, i'd like to know how to convert an ascii code to an integer, it must be pretty simple but i couldn't find it in the reference...


MyCharVariable - '0'

Ascii code IS (somehow) integer, i guess you want a number representation of the ascii code as printed number.

char outb[8];
sprintf(outb, "%d", 'a');

or do you want to transform character digits to integer?

@scjurgen :

technically, a want to send a number via serial, and light the matching led. if i understood correctly, when i send "1", will get the ascii code for "1", i want it converted to the integer "1". i know i could simply subtract 48 (the ascii code for "1" beeing 49), but i was wondering if there was any function that converts an ascii code to a char string or to the corresponding integer... dunno if i'm clear enough...

ok, understood, so you have to go with the solution of Coding Badly.

int ledNumber=val-'0'; // send character 0 to 9

the other way to do that kind of conversion is to read a string from the serial and use sscanf(); Uhm... i forgot, atoi() is a good solution too.

..and strtol.

thanks a lot guys! i got my sketch working fine :)

why is it i can't find strtol or sscanf in the reference?

yan_g: thanks a lot guys! i got my sketch working fine :)

why is it i can't find strtol or sscanf in the reference?

Because it is pretty much low-level C-programming. Therefore the arduino project does omit it; as C-programming and libraries are the base of all of the arduino stuff (limited though, i.e. printf and floating point is not supported).

You might find your ASCII to decimal conversions easier to understand and maybe easier to implement if you use the hexadecimal representations instead of the decimal representations for those codes.

For example the ASCII code for the decimal number '3' is 0110011. This can be expressed as 51 in decimal as you have been doing but in hex it is 33. Similarly the hex code for the number '4' is 34, and for all of the other numbers it is 3n. It is a simple matter to mask off the upper half of the hex code (the leading 3) to get the decimal number.

Check out the expanded [u]ASCII chart[/u] link at Scroll down to the explanation of the 'second section'.