passing a char Array to a function

Hi There, I have several character arrays which hold numeric data read from serial port

        char[] cX = new char[3]; //two digits
        char[] cY = new char[2]; / one digit
        char[] cP = new char[2]; // one digit

I want to write a single function to convert any of these three arrays into a integer value.

I know that I can convert a single character from a char array to corresponding integer/float by

    float integerFromChar(char myChar) {
      return myChar - '0';}

But I need some guidance on how to create a custom function which can transform the char array (return numeric value)

I think it's like this

int IntfromCharArray(char[] myChar) {
  float total=0;
  for (int i=0;i<(myChar.length-1);i++){
 if (myChar[i]!=' ')
 return int(total);}  

The problem is that this works fine if the character array contains a single digit - which is the case in cY and cP above, but in the case of cX it is two digits, and the program fails to give the desired output (i.e. total is incorrect)

Any help is much appreciated. Thanks Genny



  • edited June 2014 Answer ✓

    So you got an array of char digits like '3', '0', '-', '.', etc., is it?
    Just know that we can instantiate a String outta char[]:

    After all, a String object stores its characters in a char[] field internally! :-h
    After that, it's as simple as using int() or float() in order to get a number outta it:

    // passing-a-char-array-to-a-function
    char[] digits = { // -82.402
      '-', '8', '2', '.', '4', '0', '2'
    String digit = new String(digits);
    int number = int(digit);

    Shortcut: int number = int(new String(digits)); :D

  • humm, this is my try : )

    char[] cX = {
      '1', '2'
    }; //two digits
    char[] cY = {
    }; // one digit
    char[] cP = {
      '6', '8', '7'
    }; // three digit
    char[] w = {
      '6', '8', '7', '-', '6'
    }; // error
    int  toInt(char[] c) {
      String s = "";
      for (int i = 0; i < c.length; i++) {
        if (c[i] > '0' && c[i] < '9') { 
        else {
          return -1;
      return int(s);
    void setup() {
  • Thank You very much GotoLoop and _vk. I didnt know that a string could be made out of the chars!. So I think the first method makes it easier for me. So it looks like this : without the use of the custom function. I didnt add the shortcut to this, but will do so in the final version. Thanks a million!

                String cXs = new String(cX);
                 String cYs = new String(cY);
                String cPs = new String(cP);
Sign In or Register to comment.