Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Usually given a string:</p> <pre><code>char * myStr= "123"; </code></pre> <p>the way to obtain it's value as an int is:</p> <pre><code>int value=atoi(myStr); </code></pre> <p>Some things important to notice:</p> <p>the following include is necessary:</p> <pre><code>#include &lt;stdlib.h&gt; </code></pre> <p>and you must be sure that your string is a null terminated string otherwise atoi will crash you program.</p> <p>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.</p> <p>Please take a look at the code bellow:</p> <pre><code>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&lt;exp;i++){ ret*=base; } return ret; } </code></pre> <p>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.</p> <p>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.</p> <p>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:</p> <pre><code>int add=digit*power(10,exp); </code></pre> <p>to:</p> <pre><code> int add=digit*power(8,exp); </code></pre> <p>for hexadecimal this will not work, and implementation of such a function will be significantly different.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload