how can i convert a character to an integer?
e.g. char a = '8'; then convert a to an integer, so it can then be converted to binary.
i know atoi converts a string to an integer, but i cant seem to find anything to do it with chars.
how can i convert a character to an integer?
e.g. char a = '8'; then convert a to an integer, so it can then be converted to binary.
i know atoi converts a string to an integer, but i cant seem to find anything to do it with chars.
Subtract '0'.Code:char a = '8'; int i = a - '0';
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
you could use simple arithemetic on the character values too, but I'm not sure how portable that would be.Code:int ctoi(char ch) { char temp[2] = {ch, 0}; return atoi(temp); }
More portable than the code you posted.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
the encoding used may not yield the correct value using that method. for instance, using gray's code there's a single bit of difference between neighboring values - so subtracting values would probably result in an error. on the other hand, atoi() relies on the C locale mechanism for character conversion.
Okay, I am merely referring to the C language.And Gray code wouldn't work for C since C mandates a pure binary encoding.the 10 decimal digits
0 1 2 3 4 5 6 7 8 9[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
Last edited by Dave_Sinkula; 05-02-2005 at 01:39 PM.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*