conversion of string to decimal

2019-08-28 20:51发布

I am using RS232 serial communication to rotate the motor. The serial communication is done in strings but i need decimal value for it. Any clues how to proceed.I am coding in c language.i tried using atoi function but its not working.

char *p;

int z=atoi(p);

2条回答
Melony?
2楼-- · 2019-08-28 21:03

Usually given a string:

char * myStr= "123";

the way to obtain it's value as an int is:

int value=atoi(myStr);

Some things important to notice:

the following include is necessary:

#include <stdlib.h>

and you must be sure that your string is a null terminated string otherwise atoi will crash you program.

You didn't gave us much information but if you're programming a microcontroller (I suspect that since you told us about a motor) you maybe won't want to use stdlib. In that case you might have use a costum function.

Please take a look at the code bellow:

int stringToInt(char* nrStr){
int nrChars=0;
while(nrStr[nrChars]!='\0'){
    nrChars++;
}


int result=0;
int i=0;
while(nrStr[i]!='\0'){//while you dont get to the end of the string
    int digit=nrStr[i]-48;//48 is zero ascii code
    int exp=nrChars-i-1;
    int add=digit*power(10,exp);
    result+=add;
    i++;


}
return result;


}
int power(int base, int exp){
int ret=1;
int i;
for(i=0;i<exp;i++){
    ret*=base;
}
return ret;
}

This does not use any library functions and does the job. I've done it in 3 minutes and it may have some small error, it's not very efficient and does not verify possible errors, but in principle if you pass the strinToint function a well formed integer as a null terminated string it will output the correct value.

If you're using a library that does have some implementation of a power function do use it instead of the one I gave you since it is not efficient at all.

One last note: if you for some reason need to use it in other basis lets say octal basis, you have to chance the line:

int add=digit*power(10,exp);

to:

 int add=digit*power(8,exp);

for hexadecimal this will not work, and implementation of such a function will be significantly different.

查看更多
何必那么认真
3楼-- · 2019-08-28 21:03

Use the strtoXXX() family of functions. If you need int, long or long long or their unsigned variants:

long l = strtol("1234567", NULL, 10);
long long ll = strtoll("1234567", NULL, 10);
unsigned long l = strtoul("1234567", NULL, 10);

If you need a float, double, or long double use this:

float f = strtof("3.1415927", NULL);
double d = strtod("3.1415927", NULL);

Manuals here and here.

查看更多
登录 后发表回答