Post

(C) atoi / strtol , sprintf - 문자열 > 숫자, 16진수 변환

문자열 > 숫자
1
2
3
4
5
6
7
8
9
10
#include <stdlib.h>
int atoi(const char \*nptr);
long atol(const char \*nptr);
long long atoll(const char \*nptr);

  

long int strtol(const char \*nptr, char \*\*endptr, int base);    // strtoll
unsigned long int strtoul(const char \*nptr, char \*\*endptr, int base);  //strtoull

직접 변환하기

1
2
3
auto i = 0;
while (isdigit(input[pos])) i = i \* 10 + input[pos++] - '0';

숫자 > 문자열
1
2
3
4
5
#include <stdio.h>
int printf(const char \*format, ...);
int sprintf(char \*str, const char \*format, ...);
int snprintf(char \*str, size\_t size, const char \*format, ...);

shell output clear & cursor return to top
1
2
3
snprintf(&s, 0x80u, "%c[2J%c[0;0H", 27, 27);   // shell output clear
snprintf(&s, 0x80u, "%c[%d;%dH", 27, 5, 5);    // shell cursor return to top

문자열 인풋 그대로 16진수로 변환

문자열 “bfffeeac”을 integer bfffeeac로 저장
  • strtol()계열 함수를 이용해야 한다. atoi()는 16진수를 지원 안하기 때문에 a, f같은 문자 만날 시 그 전까지만 변환된다.
  • MSB까지 입력해야 하기 때문에 strtol()이 아니라 strtoul()을 이용해야 한다. strtol()을 사용하면 MSB를 제외한 31bit만 사용하기 때문에 7fffffff가 최대값이다.
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
#include <stdio.h>
#include <stdlib.h>

  

int main( int argc, char \*argv[] )
{
char str[256];
char dst[9];
unsigned int addr=0;
char\* cp;
strcpy( str, argv[1] );
strncpy( dst, argv[1], 8);
dst[8] = 0;

  

addr = strtoul(dst, NULL, 16);

  

cp = (char\*)addr;
printf( str );
printf("\naddr %p", &addr);
printf("\n\n%p : %02x %02x %02x %02x\n", cp, cp[3], cp[2], cp[1], cp[0]);
return 0;
}

shift를 이용해 직접 구현할 경우

이 경우 직접 char에 원하는 hex value를 넣어 간단히 처리했지만, 문자열로 입력받는 경우 해당 문자 그대로의 hex value를 얻는게 또 문제다. 이래 저래 strtol을 쓰는게 현명하다.

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
int main( int argc, char \*argv[] )
{
int addr=0;
char tt[4];
tt[0]=0x41;
tt[1]=0x42;
tt[2]=0x43;
tt[3]=0x44;

  

addr|=tt[3]<<24;
addr|=tt[2]<<16;
addr|=tt[1]<<8;
addr|=tt[0];

  

printf("%x", addr);

  

return 0;
}

This post is licensed under CC BY 4.0 by the author.