[C++] _tcstol, strtol, wcstol 문자열 진수 변환

오늘은 문자열을 쉽게 2진수, 10진수, 16진수로 변경할 수 있는 _tcstol 함수에 대해 알아보겠습니다.

함수 원형은 아래와 같습니다.

long strtol(
   const char *string,
   char **end_ptr,
   int base
);
long wcstol(
   const wchar_t *string,
   wchar_t **end_ptr,
   int base
);
long _strtol_l(
   const char *string,
   char **end_ptr,
   int base,
   _locale_t locale
);
long _wcstol_l(
   const wchar_t *string,
   wchar_t **end_ptr,
   int base,
   _locale_t locale
);

오버플로우가 되면 LONG_MAX또는 LONG_MIN이 반환됩니다.
3번째 인자(진수)가 2보다 작거나 32보다 크면 ERANGE , EINVAL을 반환합니다.
해당 함수는 변환이 불가능하면 0을 반환합니다. 

사용 예제는 아래와 같습니다.

#include <iostream>
#include <tchar.h>

using namespace std;

void main()
{
	TCHAR acStrToHex[10] ={_T("ABC")};
	int iHex = _tcstol(acStrToHex, NULL, 16); // 문자열 -> 16진수

	TCHAR acStrToDec[10] ={_T("1000")};
	int iDec = _tcstol(acStrToDec, NULL, 10); // 문자열 -> 10진수

	TCHAR acStrToOct[10] ={_T("275")};
	int iOct = _tcstol(acStrToOct, NULL, 8); // 문자열 -> 8진수

	TCHAR acStrToBin[10] ={_T("1010")};
	int iBin = _tcstol(acStrToBin, NULL, 2); // 문자열 -> 2진수
}

필요 헤더파일은 아래와 같습니다.

RoutineRequired header
_tcstol<tchar.h>
strtol<stdlib.h>
wcstol<stdlib.h> or <wchar.h>
_strtol_l<stdlib.h>
_wcstol_l<stdlib.h> or <wchar.h>