Generic function for StringToInteger()
LAHAYE Olivier
olivier.lahaye at cea.fr
Tue May 16 17:22:06 UTC 2017
Sometimes, it's usefull to convert a string to an integer (received by status message for example).
Unfortunately, Plymouth script module doesn't implement this into its String API.
Thus a function must be created in order to convert strings into numbers.
// This functions takes a string containing an integer as input. It returns the integer read or "#NaN" or "#Overflow"
// Author: Olivier LAHAYE
// Licence: GPL
// Input: string to convert.
// Output: numerical value or "#NaN" or "#Overflow"
// Examples:
// "" => 0
// " " => "#NaN"
// "_" => "#NaN"
// "000965" => 965
// "1.0" => "#NaN"
// "foo" => "#NaN"
fun StringToInteger(str_val) {
ref = "0123456789";
overflow_limit = 20; // Max 20 digits
// load the number string
number_length = 0;
number_string = String( str_val );
while (char[number_length] = number_string.CharAt(number_length)) {
digit[number_length] = 0;
number_length++;
if (number_length > overflow_limit) return ("#Overflow");
}
index=0;
found=0;
while ( index < 10 ) { // For each base 10 digit
for(c=0; c<number_length; c++) { // for each number_string digit
if ( char[c] == ref.CharAt(index) ) {
digit[c] = index; // Found digit #c
found++;
}
// Check if all digits have been found.
if (found == number_length)
index = 10; // Leave early the loop.
}
index++;
}
if (found < number_length) return ( "#NaN" ); // This is not a number
return_val = 0;
factor = 1;
while (number_length > 0) {
number_length--;
return_val += ( digit[number_length] * factor );
factor *= 10;
}
return( return_val );
}
// End StringToInteger()
Have Fun.
--
Olivier LAHAYE
More information about the plymouth
mailing list