Archived

This topic is now archived and is closed to further replies.

casting

This topic is 5045 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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'');

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites