Recently in the VB Serial host computer, one of the problems is: How to transfer the string received by the serial as the integer type:
For example: Receive the "12345" assignment to the variable is 12345
Validated in VC6.0 Environment: (with this handsome man's: http://zz.csdn.net/bin/logs.php)
#include <iostream.h>
#include <stdio.h>
#include <string.h>
int mi (unsigned char dat, unsigned char mi)
{
unsigned char i;
int sum = 1;
for (i=0; i<mi; i++)
{
sum = sum * DAT;
}
return sum;
}
/****************************************************
* Function: Strtoint (char *str,int result)
* Input: Unsigned string
* Output: Integral type number
*****************************************************/
int strtoint (unsigned char* str,int result)
{int i,tmp=0; I,TMP TEMP Variable
int Length=strlen ((char*) str),//strlen parameter is const char*, so the cast
i=0;
if (str[0]== '-') i=1;
for (; i<length;i++)
{
TMP = str[i]&0x0f; If an ASCII code is stored in the original array, it is converted directly 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 is:%s\n", str);
printf ("Output integer number:%d\n", result);//123
}
--------------------------------------------Split Line----------------------------
:
Here we need to use a little bit function to describe the change of the 10-in-1*100+2*10+3*1 in the system:
In the main function, verify by:
Serial port to send and receive characters converted to integers