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);
Usually given a string:
the way to obtain it's value as an int is:
Some things important to notice:
the following include is necessary:
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:
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:
to:
for hexadecimal this will not work, and implementation of such a function will be significantly different.
Use the
strtoXXX()
family of functions. If you needint
,long
orlong long
or their unsigned variants:If you need a
float
,double
, orlong double
use this:Manuals here and here.