다음은 대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 C++ 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환을 하는 핵심 함수 convertAtoI()와 convertItoA()의 소스가 자체 제작되어 포함되어 있다. 이를 이용하는 부분은 157~158째 줄에 있는
val = convertAtoI(s, srcRdx);
convertItoA((char *) ret, val, destRdx);
이다. 지원되는 진법은 2진법에서 36진법 까지이다.
- /*
- * Filename: convertRadixCPP.cpp
- * Convert radix in a interactive mode.
- *
- * Compile: cl /EHsc convertRadixCPP.cpp
- * Execute: convertRadixCPP
- *
- * Date: 2008/03/25
- * Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- */
- #include <iostream>
- #include <string>
- #include <cmath>
- using namespace std;
- #define MAX_BUF 300
- enum { FALSE, TRUE };
- struct _TOKEN {
- char a[81];
- char b[81];
- };
- void println(char s[]) {
- cout << s << endl;
- }
- void print(char s[]) {
- cout << s;
- }
- void printUsage() {
- println("Usage: convertRadixCPP");
- println("Convert radix in a interactive mode, where the maximum radix is 36.");
- }
- void printAbout() {
- println(" About: Convert radix in a interactive mode.");
- }
- void printMainMenu() {
- println(" Command: (S)etup radix, (A)bout, (Q)uit or E(x)it");
- }
- void printMainPrompt() {
- print(" Prompt> ");
- }
- void printSubMenu(int srcRadix, int destRadix) {
- char sbuf[MAX_BUF];
- sprintf(sbuf, " Convert Radix_%d to Radix_%d", srcRadix, destRadix);
- println(sbuf);
- println(" SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
- }
- void printSubPrompt() {
- print(" Input Value>> ");
- }
- char BASE36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- void convertItoA(char *pstr, long num, int radix) {
- char tmp[2];
- char ret[MAX_BUF];
- char arr[MAX_BUF];
- long q, r;
- int i, n;
- int isNegative = FALSE;
- if (num < 0L) {
- isNegative = TRUE;
- num = -num;
- }
- arr[0] = '\0';
- q = num;
- r = 0L;
- while (q >= (long) radix) {
- r = q % (long) radix;
- q = q / (long) radix;
- tmp[0] = BASE36[r];
- tmp[1] = '\0';
- strcat(arr, tmp);
- }
- tmp[0] = BASE36[q];
- tmp[1] = '\0';
- strcat(arr, tmp);
- if (isNegative) {
- strcat(arr, "-");
- }
- n = strlen(arr);
- for (i = 0; i < n; i++) {
- ret[i] = arr[n - i - 1];
- }
- ret[n] = '\0';
- strcpy(pstr, (char *) ret);
- }
- long convertAtoI(const char *pstr, int radix) {
- char tmp[2];
- long ret = 0L;
- char arr[MAX_BUF];
- long q, r;
- int isNegative = FALSE;
- int len = strlen(pstr);
- char c;
- int i;
- long val;
- c = pstr[0];
- if (c == '-') {
- isNegative = TRUE;
- }
- else if (c >= '0' && c <= '9') {
- ret = (long) (c - '0');
- }
- else if (c >= 'A' && c <= 'Z') {
- ret = (long) (c - 'A') + 10L;
- }
- else if (c >= 'a' && c <= 'z') {
- ret = (long) (c - 'a') + 10L;
- }
- if (ret >= (long) radix) {
- println(" Invalid character!");
- return ret;
- }
- for (i = 1; i < len; i++) {
- c = pstr[i];
- ret *= radix;
- if (c >= '0' && c <= '9') {
- val = (long) (c - '0');
- }
- else if (c >= 'A' && c <= 'Z') {
- val = (long) (c - 'A') + 10L;
- }
- else if (c >= 'a' && c <= 'z') {
- val = (long) (c - 'a') + 10L;
- }
- if (val >= (long) radix) {
- println(" Invalid character!");
- return ret;
- }
- ret += val;
- }
- return ret;
- }
- void convertRadix(char *pstr, char s[], int srcRdx, int destRdx) {
- long val;
- char ret[MAX_BUF];
- val = convertAtoI(s, srcRdx);
- convertItoA((char *) ret, val, destRdx);
- strcpy(pstr, ret);
- }
- void readLine(char *pdata) {
- scanf("%s", pdata);
- }
- void readTwo(struct _TOKEN *ptoken) {
- scanf("%s", ptoken->a);
- scanf("%s", ptoken->b);
- }
- void tokenize(struct _TOKEN *ptoken, const char *line, char c) {
- int len = strlen(line);
- int i;
- int from, to;
- i = 0;
- while (line[i] != c) {
- i++;
- }
- from = i;
- while (line[i] == c) {
- i++;
- }
- to = i;
- strncpy(ptoken->a, line, to - from);
- ptoken->a[to - from] = '\0';
- while (line[i] != c) {
- i++;
- }
- from = i;
- while (line[i] == c) {
- i++;
- }
- to = i;
- strncpy(ptoken->b, line, to - from);
- ptoken->b[to - from] = '\0';
- }
- void doConvert(int srcRadix, int destRadix) {
- char sbuf[MAX_BUF];
- char line[MAX_BUF];
- char cmd[MAX_BUF];
- char srcStr[MAX_BUF], destStr[MAX_BUF];
- long tmp;
- println("");
- printSubMenu(srcRadix, destRadix);
- do {
- printSubPrompt();
- readLine((char *)cmd);
- while (strlen(cmd) <= 0) {
- readLine((char *)cmd);
- }
- if (strcmp("main()", cmd) == 0) {
- return;
- }
- else if (strcmp("exit()", cmd) == 0 || strcmp("quit()", cmd) == 0) {
- exit(0);
- }
- tmp = convertAtoI(cmd, srcRadix);
- strcpy(srcStr, cmd);
- convertRadix(destStr, srcStr, srcRadix, destRadix);
- sprintf(sbuf, " ( %s )_%d ---> ( %s )_%d", srcStr, srcRadix, destStr, destRadix);
- println(sbuf);
- println("");
- } while (TRUE);
- }
- void doStart() {
- char line[MAX_BUF];
- char cmd[MAX_BUF];
- int srcRadix = 10, destRadix = 10;
- char srcStr[MAX_BUF], destStr[MAX_BUF];
- struct _TOKEN st;
- int onlyOnce = TRUE;
- do {
- println("");
- if (onlyOnce) {
- println(" The supported maximum radix is 36.");
- onlyOnce = FALSE;
- }
- printMainMenu();
- printMainPrompt();
- readLine((char *)cmd);
- while (strlen(cmd) <= 0) {
- readLine((char *)cmd);
- }
- if (strstr("qQxX", cmd) != NULL && strlen(cmd) == 1) {
- exit(0);
- }
- else if (strstr("aA", cmd) != NULL && strlen(cmd) == 1) {
- printAbout();
- }
- else if (strstr("sS", cmd) != NULL && strlen(cmd) == 1) {
- print(" Input the source and target radices (say, 16 2): ");
- readTwo((struct _TOKEN *) &st);
- srcRadix = convertAtoI(st.a, 10);
- destRadix = convertAtoI(st.b, 10);
- doConvert(srcRadix, destRadix);
- }
- } while (TRUE);
- }
- void main(int argc, char *argv[]) {
- if (argc > 1 && strcmp("-h", argv[1]) == 0) {
- printUsage();
- exit(1);
- }
- doStart();
- }
컴파일> cl /EHsc convertRadixCPP.cpp
실행> convertRadixCPP
The supported maximum radix is 36.
Command: (S)etup radix, (A)bout, (Q)uit or E(x)it
Prompt> s
Input the source and target radices (say, 16 2): 4 2
Convert Radix_4 to Radix_2
SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
Input Value>> 321
( 321 )_4 ---> ( 111001 )_2
Input Value>> main()
Command: (S)etup radix, (A)bout, (Q)uit or E(x)it
Prompt> s
Input the source and target radices (say, 16 2): 2 4
Convert Radix_2 to Radix_4
SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
Input Value>> 111001
( 111001 )_2 ---> ( 321 )_4
Input Value>> quit()
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
'프로그래밍 > C++' 카테고리의 다른 글
7비트 ASCII 코드표 만들기 예제 with C++ (0) | 2008.03.31 |
---|---|
진법(radix) 표 만들기 예제 with C++ (0) | 2008.03.30 |
황금비율(golden ratio) 구하기 with C++ (0) | 2008.03.24 |
현재 시각 알아내기 for C++ (0) | 2008.03.24 |
C++ 언어 소스 코드(소수 찾기 코드) 리팩토링 (0) | 2008.03.21 |