# Thread: Converting a character representation of an integer, to an integer value

1. ## Converting a character representation of an integer, to an integer value

I am quite new to programming (this will become obvious as you read on.. lol) and I need to make a function that will take the character representation of a number (ie. '3'), and return it's integer value (ie 3).

I did this using a switch/case statement, and it works fine. However, it seems that it might be pretty inefficient. This function is going into firmware that is loaded on to a 8051 family processor, so I need it to follow C rules strictly, and to be as efficient as possible.

Any suggestions would be appreciated!

Here is the code I created:
Code:
```int char2int(char ch)
{
int number;

switch((int)ch)
{
case 48: number = 0;
break;
case 49: number = 1;
break;
case 50: number = 2;
break;
case 51: number = 3;
break;
case 52: number = 4;
break;
case 53: number = 5;
break;
case 54: number = 6;
break;
case 55: number = 7;
break;
case 56: number = 8;
break;
case 57: number = 9;
break;
default: number = -1;
}

return number;
}```
Thanks in advance! 2. char x = '3';
return x-'0'; 3. Originally Posted by vart char x = '3';
return x-'0';
Ooh.. tricky.. LOL.. I like that.
So simple that I overlooked it! 4. Originally Posted by RATyson Ooh.. tricky.. LOL.. I like that.
So simple that I overlooked it!
Suppose you always fill your gas tank by drilling a hole in the side of your car and sticking a hose in there. If somebody showed you how to use the gas cap, would you say "Ooh, tricky?"  5. Originally Posted by brewbuck Suppose you always fill your gas tank by drilling a hole in the side of your car and sticking a hose in there. If somebody showed you how to use the gas cap, would you say "Ooh, tricky?" Ha.. no. The first line of my response was sarcasm. As soon as I saw his post, It was immediately appearant how simple the solution was. It was right there in front of me the whole time and I looked right past it.  6. Well, to have a function that does exactly the same thing as your original function, you'd need to check to see if it was a digit first. The easiest (and most portable) way to do this is to use isdigit() from <ctype.h>:
Code:
```#include <ctype.h>

int char2int(int c) {
if(isdigit(c)) return c - '0';
else return -1;
}```
Just subtracting '0' doesn't work if the character isn't a digit. Popular pages Recent additions 