본문 바로가기

프로그래밍/C언어

[C언어] 문자열 숫자로 변환 관련 함수 - strtol, strtoul, strtod

http://shaeod.tistory.com/247


문자열을 숫자로 변환하는 strtol함수, strtoul함수, strtod함수에 관한 내용입니다.


※요약

strtol : 문자열을 long 값으로 변환 합니다. 2진수, 8진수, 16진수 값을 10진수로 변환 합니다. (string to long)

strtoul : 문자열을 unsigned long 값으로 변환 합니다. (string to unsigned long)

strtod : 문자열을 double 값으로 변환 합니다. (string to double)

무작정 외우는 것보다 "string to long, string를 long형으로" 같이 외우면 더 잘 기억납니다.


※함수 원형 및 설명

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
long strtol( const char *nptr, char **endptr, int base );
//nptr : NULL로 종결되는 수식을 포함하는 문자열의 포인터
//endptr : 변환이 멈춰진 문자열의 포인터
//base : 변환될 문자열의 기수( 2, 8, 10, 16진수 선택 ) 2~36진수까지 가능
//반홥값 : 정수 값(long), 변환 실패시 0L 리턴. errno는 ERANGE로 설정
//         -2,147,483,648 ~ 2,147,483,647
 
unsigned long strtoul( const char *nptr, char **endptr, int base );
//nptr : NULL로 종결되는 수식을 포함하는 문자열의 포인터
//endptr : 변환이 멈춰진 문자열의 포인터
//base : 변환될 문자열의 기수( 2, 8, 10, 16진수 선택 ) 2~36진수까지 가능
//반홥값 : 양의 정수 값(unsigned long), 변환 실패시 0L 리턴. errno는 ERANGE로 설정
//         0~4,294,967,295
 
double strtod( const char *nptr, char **endptr );
//nptr : NULL로 종결되는 수식을 포함하는 문자열의 포인터
//endptr : 변환이 멈춰진 문자열의 포인터
//반홥값 : 실수 값(double), 변환 실패시 0.0 리턴. errno는 ERANGE로 설정
//         1.7E +/- 308 (15 digits)


각 데이터형 범위


※예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
 
int main( )
{
    char *strStrLong = "-1234567890";
    char *strStrDouble = "3.14e+100";
    char *strStrDoubleL = "1234567890123456789012345678901234567890";
    char *strString = "The answer is 50 points";
    char *stop;
 
    long nLong;
    double nDouble;
    unsigned long nULong;
 
    nLong = strtol( strStrLong, &stop, 10 );
    printf( "%d\n", nLong );
 
    nLong = strtol( strString, &stop, 10 );
    printf( "%d stop at '%s'\n", nLong, stop );
 
    nLong = strtol( &strString[14], &stop, 10 );
    printf( "%d stop at '%s'\n", nLong, stop );
 
    nULong = strtoul( strStrLong, &stop, 10 );
    printf( "%u\n", nULong );
 
    nDouble = strtod( strStrDouble, &stop );
    printf( "%.2e\n", nDouble );
 
    nDouble = strtod( strStrLong, &stop );
    printf( "%.2e\n", nDouble );
 
    nDouble = strtod( strStrDoubleL, &stop );
    printf( "%.2e\n", nDouble );
 
    //2진수, 8진수, 16진수를 10진수로 변환
    char *strStr2  = "1010";        //2진수
    char *strStr8  = "0123";        //8진수
    char *strStr16 = "0xFF";        //16진수
    int radix;
 
    radix = 2;
    nLong = strtol( strStr2, &stop, radix );
    printf( "%d\n", nLong );
 
    radix = 8;
    nLong = strtol( strStr8, &stop, radix );
    printf( "%d\n", nLong );
 
    radix = 16;
    nLong = strtol( strStr16, &stop, radix );
    printf( "%d\n", nLong );
 
    return 0;
}



'프로그래밍 > C언어' 카테고리의 다른 글

STRING 기본 구현  (0) 2015.01.16