casting

Started by
3 comments, last by Bleedthrough 20 years, 2 months ago
Can somebody tell me if I''m doing this casting right? I''m programming in C, and I''m trying to convert the char ''9'' in userInput to an int, and store it in digit. char userInput[5]; userInput[1] = ''9''; int digit = 0; digit = (int)userInput[1]; Thanks.
Advertisement
By the way, the problem I''m having is that when I print outputArray, instead of printing 9 it prints 57.
Well, you''ve just discovered one of the (many) crap things about c. The name of the ''char'' type is utterly misleading as it doesn''t represent a character at all it just represents a byte. Even worse, you the c standard doesn''t tell you if this is a signed or an unsigned byte - it is up to the compiler (although we can ignore this complication for this example.)

So when you do:

userInput[1] = ''9'';

the compiler is just turning the ''9'' into a byte, and the byte value for ascii ''9'' is 57 and the generated code is exactly the same as doing:

userInput[1] = 57;

So your cast is fine but all it is doing is converting a byte to an int which doesn''t change the value at all - it just adds a bunch of leading zeros. To get the effect you are after you actually have to do:

digit = (int)(userInput[1] - ''0'');

That is because '9' is an ASCII character. Check out www.asciitable.com. Its true value is indeed 57. '0'-'9' are integer values 48-57. 'A'-'Z' are integers 65-90. Etc. If you want to convert it to an integer, just subtract 48. [Edit - took out a load of crap.]

[Edit - Why didn't I think of CharValue - '0', like s1 suggested? Doh!]


[edited by - Agony on February 20, 2004 2:00:48 PM]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
I would do something like this instead of a cast, but that's just me...


char userInput[5];int  digit = 0;userInput[0] = '9'; //Don't forget arrays start at 0 not 1.digit = atoi(userInput[0]);


the atoi() function converts a string to an integer.


[edited by - Radagar on February 20, 2004 4:46:07 PM]
WyrmSlayer RPG - In Early Development

This topic is closed to new replies.

Advertisement