Serial Port character conversion to integer
Recently, I am working on the VB serial port host machine. One of the problems is: how to convert the string received by the serial port to an integer as is:
For example, if "12345" is assigned to the variable, it is 12345.
In the VC6.0 environment verification passed: (rely on the handsome guy: http://zz.csdn.net/bin/logs.php)
# Include
# Include
# Include
Int mi (unsigned char dat, unsigned char mi)
{
Unsigned char I;
Int sum = 1;
For (I = 0; I {
Sum = sum * dat;
}
Return sum;
}
/*************************************** *************
* Function: strtoint (char * str, int result)
* Input: unsigned string
* Output: integer
**************************************** *************/
Int strtoint (unsigned char * str, int result)
{Int I, tmp = 0; // I, tmp Temporary Variable
Int length = strlen (char *) str); // The strlen parameter is const char *, so forced conversion
I = 0;
If (str [0] = '-') I = 1;
For (; I {
Tmp = str [I] & 0x0f; // if the original array contains an ascii code, convert it to a number.
Result + = tmp * mi (10, length-i-1); // 1*100 + 2*10 + 3*1
}
If (str [0] = '-') return-result;
Return result;
}
Void main ()
{Unsigned char str [10] = "123456 ";
Int result;
Result = 0;
Result = strtoint (str, result );
Printf ("input string: % s \ n", str );
Printf ("output INTEGER: % d \ n", result); // 123
}
// ---------------------------------------------- Split line ----------------------------
:
Here we need to use a kiddie function to describe the variation of the decimal system with digits in 1*100 + 2*10 + 3*1:
Verification passed in the main function: