Public Group

#### Archived

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

# casting

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

## 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 on other sites
By the way, the problem I''m having is that when I print outputArray, instead of printing 9 it prints 57.

##### 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 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 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]

1. 1
2. 2
Rutin
19
3. 3
khawk
15
4. 4
A4L
13
5. 5

• 13
• 26
• 10
• 11
• 44
• ### Forum Statistics

• Total Topics
633744
• Total Posts
3013658
×