Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

설명

C에서 문자 숫자를 int형으로 변경하기 위해서 사용하는 atoi(3)함수의 perl버젼입니다. 인터넷 돌아다니다가 주워논걸 올립니다.

사용방법

$str = "12345";
$num = atoi($str);

코드

sub atoi
{
    my $num;
    foreach my $d (split(//, shift()))
    {
        $num = $num * 10 + $d;
    }
    return $num;
}

코드 C버젼

/*
 Copyright (C) Information Equipment co.,LTD.
 All rights reserved.
 Code by JaeHyuk Cho <mailto:minzkn@infoeq.com>
 CVSTAG="$Header: /usr/local/mutihost/joinc/modules/moniwiki/data/text/RCS/Code_2fJPerl_2fatoi,v 1.2 2007/11/28 04:37:55 root Exp root $"
*/

#include <stdio.h>

#define def_atoi_base         (10)
#define mz_is_space(m_byte)   (((m_byte) == ' ') || ((m_byte) == '\t'))
#define mz_is_decimal(m_byte) (((m_byte) >= '0') && ((m_byte) <= '9'))
#define mz_to_num(m_byte)     ((m_byte) - '0')

long int mz_strtol(const char *s_string, char **s_endptr, int s_base)
{
 long int s_result = 0l, s_power = 0l;
 int s_is_minus;
 const char *s_entry;
 while(mz_is_space(*s_string))s_string++; /* Skip <SPACE> */
 if(*s_string == '+'){s_is_minus = 0; s_string++;} /* '+' */
 else if(*s_string == '-'){s_is_minus = 1; s_string++;} /* '-' */
 else s_is_minus = 0; /* Default '+' */
 while(*s_string == '0')s_string++; /* Skip '0' */
 s_entry = s_string;
 while(mz_is_decimal(*s_string))
 { /* power max */
  s_power = (s_power == 0l) ? 1l : (s_power * ((long int)s_base));
  s_string++;
 }
 s_string = s_entry;
 while(mz_is_decimal(*s_string))
 {
  s_result += ((long int)mz_to_num(*s_string)) * s_power;
  s_power /= (long int)s_base;
  s_string++;
 }
 if(s_endptr != ((char **)0))*s_endptr = (char *)s_string;
 return(s_is_minus == 0 ? s_result : -s_result);
}

int mz_atoi(const char *s_string)
{ return((int)mz_strtol(s_string, (char **)0, def_atoi_base)); }

long mz_atol(const char *s_string)
{ return((long)mz_strtol(s_string, (char **)0, def_atoi_base)); }

int main(int s_argc, char **s_argv)
{
 int s_index;
 if(s_argc >= 2)
 {
  for(s_index = 1;s_index < s_argc;s_index++)
   (void)fprintf(stdout, "%d = mz_atoi(\"%s\");\n", mz_atoi(s_argv[s_index]), s_argv[s_index]);
 }
 else (void)fprintf(stdout, "usage: atoi <string> [...]\nexample: atoi 1234 -1234\n");
 return(0);
}

/* End of source */

변경사항