Serial port to send and receive characters converted to integers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.