0 Replies - 1637 Views - Last Post: 09 April 2012 - 12:17 PM Rate Topic: -----

#1 Aphex19   User is offline

  • Born again Pastafarian.
  • member icon

Reputation: 619
  • View blog
  • Posts: 1,873
  • Joined: 02-August 09

Simple implementation of atoi

Posted 09 April 2012 - 12:17 PM

Description: Calls strlen so include "string.h". Compiles with GCC (et cetera)._atoi takes a null terminated string and returns the integral representation. Only base 10 (decimal) values are supported and the string should contain one continous sequence of numbers (although other characters will be ignored).
int _atoi(const char *str) 
{
	int num = 0;
	unsigned int val = 1, base = 10;

	for (int i = strlen(str)-1; i >= 0; i--) {
		if (str[i] >= '0' && str[i] <= '9') {
			num += (str[i] - '0') * val;
			val *= base;
		} 
	}

	return num;
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1