1. ## Char to int!!

Hi
Let's say i have
char c = '2';
do anyone know how to get that 2 and store it in an int so that we have int x = 2 ??

2. x = atoi(c);

3. atoi() takes char *, not char. Which is to say, it takes a string.

4. Code:
`int x=c-'0';`
or if you really want to use atoi:

Code:
```char tmp[]={c,0};
int x=atoi(tmp);```

5. Ya but root4 can you explain why c-'0' is 2?? it just an operation on chars , why it gives an int??

6. A 'char' is an integer too but of a different size:
by definition sizeof(char)=1 byte, and on 32-bit systems, sizeof(int)=4 bytes.
Depending on the compiler, a char is signed or not.

7. I forgot to say a character is simply stored as a value, which interpretation
depends on the current 'encoding' (e.g. the value 65 means 'A' using the
ASCII encoding), hence c-'0'='2'-'0'=value for symbol '2' - value for symbol '0'=50-48=2
(digits and letters codes are sorted as expected, fortunately)

8. And are we supposed to know these values of the char 0 and 2 ?? because I'm a beginner And i didn't see these kind of things in class..

9. You don't have to know them, I gave the values above to explain why it works,
simply remember that if c is the code of a digit ('0'..'9') in any ASCII-compatible
encoding, then simply substract '0' to get the corresponding integer.

10. Originally Posted by Leojeen
And are we supposed to know these values of the char 0 and 2 ?? because I'm a beginner And i didn't see these kind of things in class..
No, that's the whole point in writing something like
Code:
`x = c - '0';`
You don't have to know what the value of '0' is in normal numbers - it happens to be 48 (0x30 (hex), 060 (octal) or 00110000 (binary)) in ASCII. Note that NOT all of the worlds computers uses ascii for numbers, but most do. Older style IBM machines (not PC's, but IBM mainframes and minicomputers) use something called EBCDIC, for example. I have no idea what '0' is in EBCDIC.

But for the purposes of number conversion, you need to know that 0 through 9 are consecutive, so you can always subtract '0' from a text-digit, and you have the corresponding integer value of that digit.

--
Mats

11. Ok , thanks a lot