Skip to content

Instantly share code, notes, and snippets.

@rmccullagh
Created March 27, 2015 16:33
Show Gist options
  • Select an option

  • Save rmccullagh/60f4f1dba23cc3a09f5f to your computer and use it in GitHub Desktop.

Select an option

Save rmccullagh/60f4f1dba23cc3a09f5f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <limits.h> /* for LONG_MAX, INT_MAX */
#include <stdlib.h>
#include <stdbool.h>
#define IS_ASCII_DIGIT(c) (((c >= 48) && (c <= 57)))
long __my_atoi(char* buffer)
{
if(buffer == NULL) {
return 0;
}
long ret = 0;
bool neg = false;
if(*buffer == '-') {
neg = true;
buffer++; /* advance to next position to pass ascii check */
}
while(*buffer) {
if(IS_ASCII_DIGIT(*buffer)) {
ret = ret * 10 + (*buffer - '0');
} else {
fprintf(stderr, "Fatal Error: unexpected '%c' passed to %s\n", *buffer, __func__);
exit(EXIT_FAILURE);
}
buffer++;
}
return neg ? -ret : ret;
}
int main()
{
printf("INT_MAX=%d\n", INT_MAX);
printf("LONG_MAX=%ld\n", LONG_MAX);
printf("sizeof(long long)=%zu\n", sizeof(long long));
printf("%ld\n", __my_atoi("-10004"));
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment