#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# passing a char Array to a function

edited June 2014

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

``````        char[] cX = new char; //two digits
char[] cY = new char; / one digit
char[] cP = new char; // 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]!=' ')
total=total+(myChar[i]-'0');}
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

Tagged:

• 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[]`:
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-char:A-

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:

``````// forum.processing.org/two/discussion/5629/
// passing-a-char-array-to-a-function

char[] digits = { // -82.402
'-', '8', '2', '.', '4', '0', '2'
};
println(digits);
println();

String digit = new String(digits);
println(digit);

int number = int(digit);
println(number);

exit();
``````

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

• humm, this is my try : )

``````char[] cX = {
'1', '2'
}; //two digits

char[] cY = {
'4'
}; // 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') {
s+=c[i];
}
else {
return -1;
}
}
return int(s);
}

void setup() {
println(toInt(cX));
println(toInt(cY));
println(toInt(cP));
println(toInt(w));
}
``````
• 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);
println(cXs);
String cYs = new String(cY);
println(cYs);
String cPs = new String(cP);
println(cPs);
``````