1

Im able to convert most things without a problem, a google search if needed. I cannot figure this one out, though.

I have a char array like:

char map[40] = {0,0,0,0,0,1,1,0,0,0,1,0,1... etc

I am trying to convert the char to the correct integer, but no matter what I try, I get the ascii value: 48/ 49.

I've tried quite a few different combinations of conversions and casts, but I cannot end up with a 0 or a 1, even as a char.

Can anyone help me out with this? Thanks.

Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
  • http://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c – sajas Feb 06 '14 at 06:20
  • 1
    It looks your char array is more like this: {'0','0', ... ,'1',...} as 48 and 49 are the ASCII entries for the display characters 0 and 1. Please give us more information. – ypnos Feb 06 '14 at 06:20

2 Answers2

3

The ascii range of the characters representing integers is 48 to 57 (for '0' to '9'). You should subtract the base value 48 from the character to get its integer value.

char map[40] = {'0','0','0','0','0','1','1','0','0','0','1','0','1'...};
int integerMap[40];

for ( int i = 0 ;i < 40; i++)
{
   integerMap[i] = map[i] - 48 ;
   // OR
   //integerMap[i] = map[i] - '0';


}
vathsa
  • 303
  • 1
  • 7
1

If the char is a literal, e.g. '0' (note the quotes), to convert to an int you'd have to do:

int i = map[0] - '0';

And of course a similar operation across your map array. It would also be prudent to error-check so you know the resulting int is in the range 0-9.

The reason you're getting 48/49 is because, as you noted, direct conversion of a literal like int i = (int)map[0]; gives the ASCII value of the char.

William Gaul
  • 3,181
  • 2
  • 15
  • 21