페이지

2013년 4월 29일 월요일

[라이브러리] 하나의 16진 문자를 정수로 변환하기


문자열을 숫자로 바꾸어 주는 C 표준 API는 있지만, 하나의 문자를 숫자로 바꾸어 주는 API는 없는 것 같다. 그래서 아래와 같이 문자를 정수로 바꾸어 주는 함수를 두 가지 방식으로 구현해 보았다.

#include <stdio.h>
#include <string.h>

int ctoi_v1(char c)
{
if (c >= '0' && c <= '9')
{
return (c - '0');
else if (c >= 'A' && c <= 'F')
{
return (c - 'A' + 0x0A);
}
else if (c >= 'a' && c <= 'f')
{
return (c - 'a' + 0x0A);
}
else
{
return -1;
}
}

int ctoi_v2(char c)
{
switch (c)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': return 0x0a;
case 'B': return 0x0b;
case 'C': return 0x0c;
case 'D': return 0x0d;
case 'E': return 0x0e;
case 'F': return 0x0f;
case 'a': return 0x0a;
case 'b': return 0x0b;
case 'c': return 0x0c;
case 'd': return 0x0d;
case 'e': return 0x0e;
case 'f': return 0x0f;
default: return -1;
}
}

int main(int argc, char **argv)
{
int val = -1;

if (argc != 2)
{
printf("usage: ctoi <char>\n");
return -1;
}

if (strlen(argv[1]) != 1)
{
printf("error: only one-character argument is allowed\n");
return -1;
}

val = ctoi_v2(argv[1][0]);

if (val != -1)
{
printf("%s --> 0x%02x (%d)\n", argv[1], val, val);
}
else
{
printf("%s --> non numeric character\n", argv[1]);
}

return 0;
}

댓글 없음:

댓글 쓰기

유전자 정보에 따라 단백질이 생성되는 과정

  유전 정보는 DNA에 저장되어 있으며, 이 정보는 전사(transcription) 과정을 통해 RNA로 옮겨지고, 번역(translation) 과정을 통해 단백질로 만들어집니다. 진핵생물(사람을 포함한 대부분의 고등 생물)의 유전자는 단백질 정보를...