Skip to content

Instantly share code, notes, and snippets.

@ButchDean
Last active August 29, 2015 14:12
Show Gist options
  • Save ButchDean/e606df28914ed3e6dc4f to your computer and use it in GitHub Desktop.
Save ButchDean/e606df28914ed3e6dc4f to your computer and use it in GitHub Desktop.
An efficient solution to convert a signed number character string to a signed int. Was going to put it up on Stack Overflow, but the question was closed as duplicate.
#include <stdio.h>
#include <string.h>
#include <math.h>
int my_atoi(const char* snum)
{
int idx, strIdx = 0, accum = 0, numIsNeg = 0;
const unsigned int NUMLEN = (int)strlen(snum);
/* Check if negative number and flag it. */
if(snum[0] == 0x2d)
numIsNeg = 1;
for(idx = NUMLEN - 1; idx >= 0; idx--)
{
/* Only process numbers from 0 through 9. */
if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
accum += (snum[strIdx] - 0x30) * pow(10, idx);
strIdx++;
}
/* Check flag to see if originally passed -ve number and convert result if so. */
if(!numIsNeg)
return accum;
else
return accum * -1;
}
int main()
{
/* Tests... */
printf("Returned number is: %d\n", my_atoi("34574"));
printf("Returned number is: %d\n", my_atoi("-23"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment