We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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]!=' ')
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
Answers
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! :-hAfter that, it's as simple as using int() or float() in order to get a number outta it:
Shortcut:
int number = int(new String(digits));
:Dhumm, this is my try : )
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!