Convert numbers in the form of character array to a character

Hi,

let’s say i have a character array Xchar[5] = ‘1234’
how do I assign the value 1234 into a char x? Because I want to assign the ASCII value of 1234 to char x.

Here is the code

char Xchar[5];

string xx;

//some lines are skipped
//convert string to character array

xx.toCharArray(Xchar, xx.length()+1);

//convert to char
char x = Xchar;

then i will get an error message " invalid conversion from ‘char*’ to ‘char’ because i’m assigning a character array Xchar into char x

Thanks!!!:slight_smile:

atoi will convert a string of digits into an int. 1234 won't fit into a char though - max is 255.

Converting a character string to a binary value is a common question. atoi() will do this, but what it does is very simple

int MyAtoI(char * s)
   {
    int val = 0;
    while(*s != '\0')
       { /* convert digit */
         if(!isdigit(*s))
            break;
         val = val * 10 + ( (*s) - '0');
       } /* convert digit */
   return val;
  } // MyAtoI

Left as an Exercise For The Reader: handle a leading + or - character. Handle leading or trailing spaces.

If there is anything in the above code that you don't understand (a) go read your C programming manual and (b) if that didn't help, ask for an explanation. I might reply if I see it go by, but we're pretty far in for me to see it casually.

Note that giving it a value like "CAT" will cause the value 0 to be returned; for "9CAT" it will return 9. For "1.99" it will return 1, because "." is not a digit. I often write conversion routines like this so I can issue an error message "the value you gave is not a valid number" and furthermore I can say where the error occurred. If you add code to handle a "-", for example, you may not accept a number like "1-2" (returning -12 would be an error) or --7 (returning 7 would be an error).

Note that you cannot convert "1234" to the integer value 1234 and store it in a byte, because you are limited, in a byte, to -128..+127 (char, or signed byte) or 0..255 (unsigned char). In fact, you must check the value coming back from atoi() to make sure it is in range for the place you are storing it. int can handle -32768..32767 and unsigned int 0..65535.