컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0 에서 15 까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 Ruby 소스 코드이다. 진법 변환에 필요한 함수

        convertAtoI(string, radix)
        convertItoA(number, radix)

를 Ruby 코드로 자체 작성하여 사용하였다.
(아래의 소스는 JRuby로 실행시켜도 된다.)




  1. #  Filename: makeRadixTable.rb
  2. #            Show the radix table with 10-, 2-, 8-, 16-radices.
  3. #
  4. #  Execute: ruby makeRadixTable.rb
  5. #
  6. #      Date:  2008/03/28
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  9. def println(s=nil)
  10.     if s == nil
  11.         print("\n")
  12.     else
  13.         print("%s\n" % s)
  14.     end
  15. end
  16. def printUsage()
  17.     println("Usage: ruby makeRadixTable.rb")
  18.     println("Show the radix table with 10-, 2-, 8-, 16-radices.")
  19. end
  20. def convertItoA(num, radix)
  21.     isNegative = false
  22.     if num < 0
  23.         isNegative = true
  24.         num = -num
  25.     end
  26.     arr = ""
  27.     q = num
  28.     r = 0
  29.     while q >= radix
  30.         r = q % radix
  31.         q = q / radix
  32.         arr = arr + BASE36[r..r]
  33.     end
  34.     arr = arr + BASE36[q..q]
  35.     if isNegative
  36.         arr = arr + "-"
  37.     end
  38.     n = arr.length
  39.     ret = ""
  40.     for i in 0...n
  41.         ret = ret + arr[(n - i - 1)..(n - i - 1)]
  42.     end
  43.     return ret
  44. end
  45. def convertAtoI(srcStr, radix)
  46.     isNegative = false
  47.     ret = 0
  48.     len = srcStr.length
  49.     val = 0
  50.     c = srcStr[0..0]
  51.     if c == '-'
  52.         isNegative = true
  53.     elsif c >= '0' and c <= '9'
  54.         ret = c[0] - '0'[0]
  55.     elsif c >= 'A' and c <= 'Z'
  56.         ret = (c[0] - 'A'[0]) + 10
  57.     elsif c >= 'a' and c <= 'z'
  58.         ret = (c[0] - 'a'[0]) + 10
  59.     end
  60.     if ret >= radix
  61.         println("        Invalid character!")
  62.         return ret
  63.     end
  64.     for i in 1...len
  65.         c = srcStr[i..i]
  66.         ret = ret * radix
  67.         if c >= '0' and c <= '9'
  68.             val = c[0] - '0'[0]
  69.         elsif c >= 'A' and c <= 'Z'
  70.             val = (c[0] - 'A'[0]) + 10
  71.         elsif c >= 'a' and c <= 'z'
  72.             val = (c[0] - 'a'[0]) + 10
  73.         end
  74.         if val >= radix
  75.             println("        Invalid character!")
  76.             return ret
  77.         end
  78.         ret = ret + val
  79.     end
  80.     return ret
  81. end
  82. def makeTable()
  83.     sbuf = ""
  84.     abuf = ""
  85.     tbuf = ""
  86.     for i in 0...4
  87.         sbuf += "+-------"
  88.     end
  89.     sbuf += "+"
  90.     println(sbuf)
  91.     sbuf = "|  Dec"
  92.     sbuf += "\t|   Bin"
  93.     sbuf += "\t|  Oct"
  94.     sbuf += "\t|  Hex  |"
  95.     println(sbuf)
  96.     sbuf = ""
  97.     for i in 0...4
  98.         sbuf += "+-------"
  99.     end
  100.     sbuf += "+"
  101.     println(sbuf)
  102.     for i in 0...16
  103.         sbuf = "|   %2d" % i
  104.         abuf = convertItoA(i, 2)
  105.         tbuf = "\t|  %4s" % abuf
  106.         sbuf += tbuf
  107.         abuf = convertItoA(i, 8)
  108.         tbuf = "\t|   %2s" % abuf
  109.         sbuf += tbuf
  110.         abuf = convertItoA(i, 16)
  111.         tbuf = "\t|    %-2s |" % abuf
  112.         sbuf += tbuf
  113.         println(sbuf)
  114.     end
  115.     sbuf = ""
  116.     for i in 0...4
  117.         sbuf += "+-------"
  118.     end
  119.     sbuf += "+"
  120.     println(sbuf)
  121. end
  122. if ARGV.length > 0 and "-h" == ARGV[0]
  123.     printUsage()
  124.     exit(1)
  125. end
  126. makeTable()



실행> ruby makeRadixTable.rb

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0 에서 15 까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 Python 소스 코드이다. 진법 변환에 필요한 함수

        convertAtoI(string, radix)
        convertItoA(number, radix)

를 Python 코드로 자체 작성하여 사용하였다.

(아래의 소스는 Jython이나 IronPython에서도 수정없이 그대로 실행된다.)



  1. #  Filename: makeRadixTable.py
  2. #            Show the radix table with 10-, 2-, 8-, 16-radices.
  3. #
  4. #  Execute: python makeRadixTable.py
  5. #
  6. #      Date:  2008/03/28
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import sys
  9. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10. def println(s=None):
  11.     if s == None:
  12.         print
  13.     else:
  14.         print(s)
  15. def printUsage():
  16.     println("Usage: python makeRadixTable.py")
  17.     println("Show the radix table with 10-, 2-, 8-, 16-radices.")
  18. def convertItoA(num, radix):
  19.     isNegative = False
  20.     if num < 0:
  21.         isNegative = True
  22.         num = -num
  23.     arr = ""
  24.     q = num
  25.     r = 0
  26.     while q >= radix:
  27.         r = q % radix
  28.         q = q / radix
  29.         arr += BASE36[r]
  30.     arr += BASE36[q]
  31.     if isNegative:
  32.         arr += "-"
  33.     n = len(arr)
  34.     ret = ""
  35.     for i in range(0, n):
  36.         ret += arr[n - i - 1]
  37.     return ret
  38. def convertAtoI(srcStr, radix):
  39.     isNegative = False
  40.     ret = 0
  41.     m = len(srcStr)
  42.     val = 0
  43.     c = srcStr[0]
  44.     if c == '-':
  45.         isNegative = True
  46.     elif c >= '0' and c <= '9':
  47.         ret = ord(c) - ord('0')
  48.     elif c >= 'A' and c <= 'Z':
  49.         ret = (ord(c) - ord('A')) + 10
  50.     elif c >= 'a' and c <= 'z':
  51.         ret = (ord(c) - ord('a')) + 10
  52.     if ret >= radix:
  53.         println("        Invalid character!")
  54.         return ret
  55.     for i in range(1, m):
  56.         c = srcStr[i]
  57.         ret *= radix
  58.         if c >= '0' and c <= '9':
  59.             val = ord(c) - ord('0')
  60.         elif c >= 'A' and c <= 'Z':
  61.             val = (ord(c) - ord('A')) + 10
  62.         elif c >= 'a' and c <= 'z':
  63.             val = (ord(c) - ord('a')) + 10
  64.         if val >= radix:
  65.             println("        Invalid character!")
  66.             return ret
  67.         ret += val
  68.     return ret
  69. def makeTable():
  70.     sbuf = ""
  71.     abuf = ""
  72.     tbuf = ""
  73.     for i in range(0, 4):
  74.         sbuf += "+-------"
  75.     sbuf += "+"
  76.     println(sbuf)
  77.     sbuf = "|  Dec"
  78.     sbuf += "\t|   Bin"
  79.     sbuf += "\t|  Oct"
  80.     sbuf += "\t|  Hex  |"
  81.     println(sbuf)
  82.     sbuf = ""
  83.     for i in range(0, 4):
  84.         sbuf += "+-------"
  85.     sbuf += "+"
  86.     println(sbuf)
  87.     for i in range(0, 16):
  88.         sbuf = "|   %2d" % i
  89.         abuf = convertItoA(i, 2)
  90.         tbuf = "\t|  %4s" % abuf
  91.         sbuf += tbuf
  92.         abuf = convertItoA(i, 8)
  93.         tbuf = "\t|   %2s" % abuf
  94.         sbuf += tbuf
  95.         abuf = convertItoA(i, 16)
  96.         tbuf = "\t|    %-2s |" % abuf
  97.         sbuf += tbuf
  98.         println(sbuf)
  99.     sbuf = ""
  100.     for i in range(0, 4):
  101.         sbuf += "+-------"
  102.     sbuf += "+"
  103.     println(sbuf)
  104. if len(sys.argv) > 1 and "-h" == sys.argv[1]:
  105.     printUsage()
  106.     sys.exit(1)
  107. makeTable()



실행> python makeRadixTable.py

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0 에서 15 까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 Groovy 소스 코드이다. 진법 변환에 필요한 메소드로는 자바에

         Integer.parseInt(String, int radix);
         Long.toString(long, int radix);

가 이미 있지만, 여기에 준하는 함수

        convertAtoI(String, radix)
        convertItoA(long, radix)

를 Groovy 코드로 자체 작성하여 사용하였다.



  1. /*
  2.  *  Filename: makeRadixTable.groovy
  3.  *            Show the radix table with 10-, 2-, 8-, 16-radices.
  4.  *
  5.  *  Execute: groovy makeRadixTable.groovy
  6.  *
  7.  *      Date:  2008/03/28
  8.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  9.  */
  10. def printUsage() {
  11.     println("Usage: groovy makeRadixTable.groovy")
  12.     println("Show the radix table with 10-, 2-, 8-, 16-radices.")
  13. }
  14. def convertItoA(long num, int radix) {
  15.     String BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  16.     long q, r
  17.     boolean isNegative = false
  18.     if (num < 0) {
  19.         isNegative = true
  20.         num = -num
  21.     }
  22.     def arr = ""
  23.     q = num
  24.     r = 0
  25.     while (q >= radix) {
  26.         r = q % radix
  27.         q = q / radix
  28.         arr += BASE36[(int) r]
  29.      }
  30.      arr += BASE36[(int) q]
  31.      if (isNegative) {
  32.          arr += "-"
  33.      }
  34.      int n = arr.length()
  35.      def ret = ""
  36.      for (i = 0; i < n; i++) {
  37.          ret += arr[n - i - 1]
  38.      }
  39.      return ret
  40. }
  41. def convertAtoI(String srcStr, int radix) {
  42.     String BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  43.     boolean isNegative = false
  44.     long ret = 0L
  45.     int len = srcStr.length()
  46.     String c
  47.     int i
  48.     long val = 0L
  49.     c = srcStr[0]
  50.     if (c == '-') {
  51.         isNegative = true
  52.     }
  53.     else if (c >= '0' && c <= '9') {
  54.         ret = (long) (c.charAt(0) - '0'.charAt(0))
  55.     }
  56.     else if (c >= 'A' && c <= 'Z') {
  57.         ret = (long) (c.charAt(0) - 'A'.charAt(0)) + 10L
  58.     }
  59.     else if (c >= 'a' && c <= 'z') {
  60.         ret = (long) (c.charAt(0) - 'a'.charAt(0)) + 10L
  61.     }
  62.     if (ret >= (long) radix) {
  63.         println("        Invalid character!")
  64.         return ret
  65.     }
  66.     for (i = 1; i < len; i++) {
  67.         c = srcStr[i]
  68.         ret *= radix
  69.         if (c >= '0' && c <= '9') {
  70.             val = (long) (c.charAt(0) - '0'.charAt(0))
  71.         }
  72.         else if (c >= 'A' && c <= 'Z') {
  73.             val = (long) (c.charAt(0) - 'A'.charAt(0)) + 10L
  74.         }
  75.         else if (c >= 'a' && c <= 'z') {
  76.             val = (long) (c.charAt(0) - 'a'.charAt(0)) + 10L
  77.         }
  78.         if (val >= (long) radix) {
  79.             println("        Invalid character!")
  80.             return ret
  81.         }
  82.         ret += val
  83.     }
  84.     return ret
  85. }
  86. def makeTable() {
  87.     String sbuf = ""
  88.     String abuf = ""
  89.     String tbuf = ""
  90.     int i, j
  91.     char c;
  92.     for (i = 0; i < 4; i++) {
  93.         print("+-------")
  94.     }
  95.     print("+")
  96.     println("")
  97.     print("|  Dec")
  98.     print("\t|   Bin")
  99.     print("\t|  Oct")
  100.     print("\t|  Hex  |")
  101.     println("")
  102.     for (i = 0; i < 4; i++) {
  103.         print("+-------")
  104.     }
  105.     print("+")
  106.     println("")
  107.     for (i = 0; i < 16; i++) {
  108.         sbuf = String.format("|   %2d", i)
  109.         abuf = convertItoA((long) i, 2)
  110.         tbuf = String.format("\t|  %4s", abuf)
  111.         sbuf += tbuf
  112.         abuf = convertItoA((long) i, 8)
  113.         tbuf = String.format("\t|   %2s", abuf)
  114.         sbuf += tbuf
  115.         abuf = convertItoA((long) i, 16)
  116.         tbuf = String.format("\t|    %-2s |", abuf)
  117.         sbuf += tbuf
  118.         println(sbuf)
  119.     }
  120.     for (i = 0; i < 4; i++) {
  121.         print("+-------")
  122.     }
  123.     print("+")
  124.     println("")
  125. }
  126. if (args.length > 0 && "-h".equals(args[0])) {
  127.     printUsage()
  128.     System.exit(1);
  129. }
  130. makeTable()



실행> groovy makeRadixTable.groovy

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0부터 15까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 자바 소스 코드이다. 진법 변환에 필요한 메소드로는 자바에

         Integer.parseInt(String, int radix);
         Long.toString(long, int radix);

가 이미 있지만, 여기에 준하는 메소드

        convertAtoI(String, radix)
        convertItoA(long, radix)

를 자체 작성하여 사용하였다.



  1. /*
  2.  *  Filename: MakeRadixTableApp.java
  3.  *            Show the radix table with 10-, 2-, 8-, 16-radices.
  4.  *
  5.  *  Compile: javac -d . MakeRadixTableApp.java
  6.  *  Execute: java MakeRadixTableApp
  7.  *
  8.  *      Date:  2008/03/27
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. public class MakeRadixTableApp {
  12.     static void println(String s) {
  13.         System.out.println(s);
  14.     }
  15.     static void print(String s) {
  16.         System.out.print(s);
  17.     }
  18.     static void printUsage() {
  19.         println("Usage: java MakeRadixTableApp");
  20.         println("Show the radix table with 10-, 2-, 8-, 16-radices.");
  21.     }
  22.     static String BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  23.     public static String convertItoA(long num, int radix) {
  24.         long q, r;
  25.         boolean isNegative = false;
  26.         if (num < 0L) {
  27.             isNegative = true;
  28.             num = -num;
  29.         }
  30.         String arr = "";
  31.         q = num;
  32.         r = 0L;
  33.         while (q >= (long) radix) {
  34.             r = q % (long) radix;
  35.             q = q / (long) radix;
  36.             arr += BASE36.charAt((int) r);
  37.         }
  38.         arr += BASE36.charAt((int) q);
  39.         if (isNegative) {
  40.              arr += "-";
  41.         }
  42.         int n = arr.length();
  43.         String ret = "";
  44.         for (int i = 0; i < n; i++) {
  45.             ret += arr.charAt(n - i - 1);
  46.         }
  47.         return ret;
  48.     }
  49.     public static long convertAtoI(String srcStr, int radix) {
  50.         boolean isNegative = false;
  51.         long ret = 0L;
  52.         int len = srcStr.length();
  53.         char c;
  54.         int i;
  55.         long val = 0L;
  56.         c = srcStr.charAt(0);
  57.         if (c == '-') {
  58.            isNegative = true;
  59.         }
  60.         else if (c >= '0' && c <= '9') {
  61.             ret = (long) (c - '0');
  62.         }
  63.         else if (c >= 'A' && c <= 'Z') {
  64.             ret = (long) (c - 'A') + 10L;
  65.         }
  66.         else if (c >= 'a' && c <= 'z') {
  67.             ret = (long) (c - 'a') + 10L;
  68.         }
  69.         if (ret >= (long) radix) {
  70.             println("        Invalid character!");
  71.             return ret;
  72.         }
  73.         for (i = 1; i < len; i++) {
  74.             c = srcStr.charAt(i);
  75.             ret *= radix;
  76.             if (c >= '0' && c <= '9') {
  77.                 val = (long) (c - '0');
  78.             }
  79.             else if (c >= 'A' && c <= 'Z') {
  80.                 val = (long) (c - 'A') + 10L;
  81.             }
  82.             else if (c >= 'a' && c <= 'z') {
  83.                 val = (long) (c - 'a') + 10L;
  84.             }
  85.             if (val >= (long) radix) {
  86.                 println("        Invalid character!");
  87.                 return ret;
  88.             }
  89.             ret += val;
  90.         }
  91.         return ret;
  92.     }
  93.     public static void makeTable() {
  94.         String sbuf = "";
  95.         String abuf = "";
  96.         String tbuf = "";
  97.         int i, j;
  98.         char c;
  99.         for (i = 0; i < 4; i++) {
  100.             print("+-------");
  101.         }
  102.         print("+");
  103.         println("");
  104.         print("|  Dec");
  105.         print("\t|   Bin");
  106.         print("\t|  Oct");
  107.         print("\t|  Hex  |");
  108.         println("");
  109.         for (i = 0; i < 4; i++) {
  110.             print("+-------");
  111.         }
  112.         print("+");
  113.         println("");
  114.         for (i = 0; i < 16; i++) {
  115.             sbuf = String.format("|   %2d", i);
  116.             abuf = convertItoA((long) i, 2);
  117.             tbuf = String.format("\t|  %4s", abuf);
  118.             sbuf += tbuf;
  119.             abuf = convertItoA((long) i, 8);
  120.             tbuf = String.format("\t|   %2s", abuf);
  121.             sbuf += tbuf;
  122.             abuf = convertItoA((long) i, 16);
  123.             tbuf = String.format("\t|    %-2s |", abuf);
  124.             sbuf += tbuf;
  125.             println(sbuf);
  126.         }
  127.         for (i = 0; i < 4; i++) {
  128.             print("+-------");
  129.         }
  130.         print("+");
  131.         println("");
  132.     }
  133.     public static void main(String[] args) {
  134.         if (args.length > 0 && "-h".equals(args[0])) {
  135.             printUsage();
  136.             System.exit(1);
  137.         }
  138.         makeTable();
  139.     }
  140. }



컴파일> javac -d . MakeRadixTableApp.java

실행> java MakeRadixTableApp

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

다음은  대화형 모드(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진법 까지이다.



  1. /*
  2.  *  Filename: convertRadixCPP.cpp
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Compile: cl /EHsc convertRadixCPP.cpp
  6.  *  Execute: convertRadixCPP
  7.  *
  8.  *      Date:  2008/03/25
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. #include <iostream>
  12. #include <string>
  13. #include <cmath>
  14. using namespace std;
  15. #define MAX_BUF 300
  16. enum { FALSE, TRUE };
  17. struct _TOKEN {
  18.     char a[81];
  19.     char b[81];
  20. };
  21. void println(char s[]) {
  22.     cout << s << endl;
  23. }
  24. void print(char s[]) {
  25.     cout << s;
  26. }
  27. void printUsage() {
  28.     println("Usage: convertRadixCPP");
  29.     println("Convert radix in a interactive mode, where the maximum radix is 36.");
  30. }
  31. void printAbout() {
  32.     println("    About: Convert radix in a interactive mode.");
  33. }
  34. void printMainMenu() {
  35.     println("  Command: (S)etup radix, (A)bout, (Q)uit or E(x)it");
  36. }
  37. void printMainPrompt() {
  38.     print("  Prompt> ");
  39. }
  40. void printSubMenu(int srcRadix, int destRadix) {
  41.     char sbuf[MAX_BUF];
  42.     sprintf(sbuf, "    Convert Radix_%d to Radix_%d", srcRadix, destRadix);
  43.     println(sbuf);
  44.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
  45. }
  46. void printSubPrompt() {
  47.     print("    Input Value>> ");
  48. }
  49. char BASE36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  50. void convertItoA(char *pstr, long num, int radix) {
  51.    char tmp[2];
  52.    char ret[MAX_BUF];
  53.    char arr[MAX_BUF];
  54.    long q, r;
  55.    int i, n;
  56.    int isNegative = FALSE;
  57.    if (num < 0L) {
  58.       isNegative = TRUE;
  59.       num = -num;
  60.    }
  61.    arr[0] = '\0';
  62.    q = num;
  63.    r = 0L;
  64.    while (q >= (long) radix) {
  65.       r = q % (long) radix;
  66.       q = q / (long) radix;
  67.       tmp[0] = BASE36[r];
  68.       tmp[1] = '\0';
  69.       strcat(arr, tmp);
  70.    }
  71.    tmp[0] = BASE36[q];
  72.    tmp[1] = '\0';
  73.    strcat(arr, tmp);
  74.    if (isNegative) {
  75.       strcat(arr, "-");
  76.    }
  77.     n = strlen(arr);
  78.     for (i = 0; i < n; i++) {
  79.         ret[i] = arr[n - i - 1];
  80.     }
  81.     ret[n] = '\0';
  82.     strcpy(pstr, (char *) ret);
  83. }
  84. long convertAtoI(const char *pstr, int radix) {
  85.     char tmp[2];
  86.     long ret = 0L;
  87.     char arr[MAX_BUF];
  88.     long q, r;
  89.     int isNegative = FALSE;
  90.     int len = strlen(pstr);
  91.     char c;
  92.     int i;
  93.     long val;
  94.     c = pstr[0];
  95.     if (c == '-') {
  96.         isNegative = TRUE;
  97.     }
  98.     else if (c >= '0' && c <= '9') {
  99.         ret = (long) (c - '0');
  100.     }
  101.     else if (c >= 'A' && c <= 'Z') {
  102.         ret = (long) (c - 'A') + 10L;
  103.     }
  104.     else if (c >= 'a' && c <= 'z') {
  105.         ret = (long) (c - 'a') + 10L;
  106.     }
  107.     if (ret >= (long) radix) {
  108.         println("        Invalid character!");
  109.         return ret;
  110.     }
  111.     for (i = 1; i < len; i++) {
  112.         c = pstr[i];
  113.         ret *= radix;
  114.         if (c >= '0' && c <= '9') {
  115.             val = (long) (c - '0');
  116.         }
  117.         else if (c >= 'A' && c <= 'Z') {
  118.             val = (long) (c - 'A') + 10L;
  119.         }
  120.         else if (c >= 'a' && c <= 'z') {
  121.             val = (long) (c - 'a') + 10L;
  122.         }
  123.         if (val >= (long) radix) {
  124.             println("        Invalid character!");
  125.             return ret;
  126.         }
  127.         ret += val;
  128.     }
  129.     return ret;
  130. }
  131. void convertRadix(char *pstr, char s[],  int srcRdx, int destRdx) {
  132.     long val;
  133.     char ret[MAX_BUF];
  134.     val = convertAtoI(s, srcRdx);
  135.     convertItoA((char *) ret, val, destRdx);
  136.     strcpy(pstr, ret);
  137. }
  138. void readLine(char *pdata) {
  139.     scanf("%s", pdata);
  140. }
  141. void readTwo(struct _TOKEN *ptoken) {
  142.     scanf("%s", ptoken->a);
  143.     scanf("%s", ptoken->b);
  144. }
  145. void tokenize(struct _TOKEN *ptoken, const char *line, char c) {
  146.     int len = strlen(line);
  147.     int i;
  148.     int from, to;
  149.     i = 0;
  150.     while (line[i] != c) {
  151.         i++;
  152.     }
  153.     from = i;
  154.     while (line[i] == c) {
  155.         i++;
  156.     }
  157.     to = i;
  158.     strncpy(ptoken->a, line, to - from);
  159.     ptoken->a[to - from] = '\0';
  160.     while (line[i] != c) {
  161.         i++;
  162.     }
  163.     from = i;
  164.     while (line[i] == c) {
  165.         i++;
  166.     }
  167.     to = i;
  168.     strncpy(ptoken->b, line, to - from);
  169.     ptoken->b[to - from] = '\0';
  170. }
  171. void doConvert(int srcRadix, int destRadix) {
  172.     char sbuf[MAX_BUF];
  173.     char line[MAX_BUF];
  174.     char cmd[MAX_BUF];
  175.     char srcStr[MAX_BUF], destStr[MAX_BUF];
  176.     long tmp;
  177.     println("");
  178.     printSubMenu(srcRadix, destRadix);
  179.     do {
  180.         printSubPrompt();
  181.         readLine((char *)cmd);
  182.         while (strlen(cmd) <= 0) {
  183.             readLine((char *)cmd);
  184.         }
  185.         if (strcmp("main()", cmd) == 0) {
  186.             return;
  187.         }
  188.         else if (strcmp("exit()", cmd) == 0 || strcmp("quit()", cmd) == 0) {
  189.             exit(0);
  190.         }
  191.         tmp = convertAtoI(cmd, srcRadix);
  192.         strcpy(srcStr, cmd);
  193.         convertRadix(destStr, srcStr, srcRadix, destRadix);
  194.         sprintf(sbuf, "        ( %s )_%d   --->   ( %s )_%d", srcStr, srcRadix, destStr, destRadix);
  195.         println(sbuf);
  196.         println("");
  197.     } while (TRUE);
  198. }
  199. void doStart() {
  200.     char line[MAX_BUF];
  201.     char cmd[MAX_BUF];
  202.     int srcRadix = 10, destRadix = 10;
  203.     char srcStr[MAX_BUF], destStr[MAX_BUF];
  204.     struct _TOKEN st;
  205.     int onlyOnce = TRUE;
  206.     do {
  207.         println("");
  208.         if (onlyOnce) {
  209.             println("  The supported maximum radix is 36.");
  210.             onlyOnce = FALSE;
  211.         }
  212.         printMainMenu();
  213.         printMainPrompt();
  214.         readLine((char *)cmd);
  215.         while (strlen(cmd) <= 0) {
  216.             readLine((char *)cmd);
  217.         }
  218.         if (strstr("qQxX", cmd) != NULL && strlen(cmd) == 1) {
  219.             exit(0);
  220.         }
  221.         else if (strstr("aA", cmd) != NULL && strlen(cmd) == 1) {
  222.             printAbout();
  223.         }
  224.         else if (strstr("sS", cmd) != NULL && strlen(cmd) == 1) {
  225.             print("  Input the source and target radices (say, 16 2): ");
  226.             readTwo((struct _TOKEN *) &st);
  227.             srcRadix = convertAtoI(st.a, 10);
  228.             destRadix = convertAtoI(st.b, 10);
  229.             doConvert(srcRadix, destRadix);
  230.         }
  231.     } while (TRUE);
  232. }
  233. void main(int argc, char *argv[]) {
  234.     if (argc > 1 && strcmp("-h", argv[1]) == 0) {
  235.         printUsage();
  236.         exit(1);
  237.     }
  238.     doStart();
  239. }




컴파일> 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()





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 C 소스 코드이다.
(Ch를 이용하면 컴파일 하지 않고 소스를 그대로 실행시킬 수 있다.)
메뉴는 주메뉴 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()의 소스가 자체 제작되어 포함되어 있다. 이를 이용하는 부분은 153~154째 줄에 있는

         val = convertAtoI(s, srcRdx);
         convertItoA((char *) ret, val, destRdx);

이다. 지원되는 진법은 2진법에서 36진법 까지이다.



  1. /*
  2.  *  Filename: convertRadix.c
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Compile: cl convertRadix.c
  6.  *  Execute: convertRadix
  7.  *
  8.  *      Date:  2008/03/25
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <math.h>
  14. #define MAX_BUF 300
  15. enum { FALSE, TRUE };
  16. struct _TOKEN {
  17.     char a[81];
  18.     char b[81];
  19. };
  20. void println(char s[]) {
  21.     printf("%s\n", s);
  22. }
  23. void print(char s[]) {
  24.     printf("%s", s);
  25. }
  26. void printUsage() {
  27.     println("Usage: convertRadix");
  28.     println("Convert radix in a interactive mode, where the maximum radix is 36.");
  29. }
  30. void printAbout() {
  31.     println("    About: Convert radix in a interactive mode.");
  32. }
  33. void printMainMenu() {
  34.     println("  Command: (S)etup radix, (A)bout, (Q)uit or E(x)it");
  35. }
  36. void printMainPrompt() {
  37.     print("  Prompt> ");
  38. }
  39. void printSubMenu(int srcRadix, int destRadix) {
  40.     char sbuf[MAX_BUF];
  41.     sprintf(sbuf, "    Convert Radix_%d to Radix_%d", srcRadix, destRadix);
  42.     println(sbuf);
  43.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
  44. }
  45. void printSubPrompt() {
  46.     print("    Input Value>> ");
  47. }
  48. char BASE36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  49. void convertItoA(char *pstr, long num, int radix) {
  50.     char tmp[2];
  51.     char ret[MAX_BUF];
  52.     char arr[MAX_BUF];
  53.     long q, r;
  54.     int i, n;
  55.     int isNegative = FALSE;
  56.     if (num < 0L) {
  57.         isNegative = TRUE;
  58.         num = -num;
  59.     }
  60.     arr[0] = '\0';
  61.     q = num;
  62.     r = 0L;
  63.     while (q >= (long) radix) {
  64.         r = q % (long) radix;
  65.         q = q / (long) radix;
  66.         tmp[0] = BASE36[r];
  67.         tmp[1] = '\0';
  68.         strcat(arr, tmp);
  69.     }
  70.     tmp[0] = BASE36[q];
  71.     tmp[1] = '\0';
  72.     strcat(arr, tmp);
  73.     if (isNegative) {
  74.         strcat(arr, "-");
  75.     }
  76.     n = strlen(arr);
  77.     for (i = 0; i < n; i++) {
  78.         ret[i] = arr[n - i - 1];
  79.     }
  80.     ret[n] = '\0';
  81.     strcpy(pstr, (char *) ret);
  82. }
  83. long convertAtoI(const char *pstr, int radix) {
  84.     long ret = 0L;
  85.     char arr[MAX_BUF];
  86.     long q, r;
  87.     int isNegative = FALSE;
  88.     int len = strlen(pstr);
  89.     char c;
  90.     int i;
  91.     long val;
  92.     c = pstr[0];
  93.     if (c == '-') {
  94.         isNegative = TRUE;
  95.     }
  96.     else if (c >= '0' && c <= '9') {
  97.         ret = (long) (c - '0');
  98.     }
  99.     else if (c >= 'A' && c <= 'Z') {
  100.         ret = (long) (c - 'A') + 10L;
  101.     }
  102.     else if (c >= 'a' && c <= 'z') {
  103.         ret = (long) (c - 'a') + 10L;
  104.     }
  105.     if (ret >= (long) radix) {
  106.         println("        Invalid character!");
  107.         return ret;
  108.     }
  109.     for (i = 1; i < len; i++) {
  110.         c = pstr[i];
  111.         ret *= radix;
  112.         if (c >= '0' && c <= '9') {
  113.             val = (long) (c - '0');
  114.         }
  115.         else if (c >= 'A' && c <= 'Z') {
  116.             val = (long) (c - 'A') + 10L;
  117.         }
  118.         else if (c >= 'a' && c <= 'z') {
  119.             val = (long) (c - 'a') + 10L;
  120.         }
  121.         if (val >= (long) radix) {
  122.             println("        Invalid character!");
  123.             return ret;
  124.         }
  125.         ret += val;
  126.     }
  127.     return ret;
  128. }
  129. void convertRadix(char *pstr, char s[],  int srcRdx, int destRdx) {
  130.     long val;
  131.     char ret[MAX_BUF];
  132.     val = convertAtoI(s, srcRdx);
  133.     convertItoA((char *) ret, val, destRdx);
  134.     strcpy(pstr, ret);
  135. }
  136. void readLine(char *pdata) {
  137.     scanf("%s", pdata);
  138. }
  139. void readTwo(struct _TOKEN *ptoken) {
  140.     scanf("%s", ptoken->a);
  141.     scanf("%s", ptoken->b);
  142. }
  143. void tokenize(struct _TOKEN *ptoken, const char *line, char c) {
  144.     int len = strlen(line);
  145.     int i;
  146.     int from, to;
  147.     i = 0;
  148.     while (line[i] != c) {
  149.         i++;
  150.     }
  151.     from = i;
  152.     while (line[i] == c) {
  153.         i++;
  154.     }
  155.     to = i;
  156.     strncpy(ptoken->a, line, to - from);
  157.     ptoken->a[to - from] = '\0';
  158.     while (line[i] != c) {
  159.         i++;
  160.     }
  161.     from = i;
  162.     while (line[i] == c) {
  163.         i++;
  164.     }
  165.     to = i;
  166.     strncpy(ptoken->b, line, to - from);
  167.     ptoken->b[to - from] = '\0';
  168. }
  169. void doConvert(int srcRadix, int destRadix) {
  170.     char sbuf[MAX_BUF];
  171.     char line[MAX_BUF];
  172.     char cmd[MAX_BUF];
  173.     char srcStr[MAX_BUF], destStr[MAX_BUF];
  174.     long tmp;
  175.     println("");
  176.     printSubMenu(srcRadix, destRadix);
  177.     do {
  178.         printSubPrompt();
  179.         readLine((char *)cmd);
  180.         while (strlen(cmd) <= 0) {
  181.             readLine((char *)cmd);
  182.         }
  183.         if (strcmp("main()", cmd) == 0) {
  184.             return;
  185.         }
  186.         else if (strcmp("exit()", cmd) == 0 || strcmp("quit()", cmd) == 0) {
  187.             exit(0);
  188.         }
  189.         tmp = convertAtoI(cmd, srcRadix);
  190.         strcpy(srcStr, cmd);
  191.         convertRadix(destStr, srcStr, srcRadix, destRadix);
  192.         sprintf(sbuf, "        ( %s )_%d   --->   ( %s )_%d", srcStr, srcRadix, destStr, destRadix);
  193.         println(sbuf);
  194.         println("");
  195.     } while (TRUE);
  196. }
  197. void doStart() {
  198.     char line[MAX_BUF];
  199.     char cmd[MAX_BUF];
  200.     int srcRadix = 10, destRadix = 10;
  201.     char srcStr[MAX_BUF], destStr[MAX_BUF];
  202.     struct _TOKEN st;
  203.     int onlyOnce = TRUE;
  204.     do {
  205.         println("");
  206.         if (onlyOnce) {
  207.             println("  The supported maximum radix is 36.");
  208.             onlyOnce = FALSE;
  209.         }
  210.         printMainMenu();
  211.         printMainPrompt();
  212.         readLine((char *)cmd);
  213.         while (strlen(cmd) <= 0) {
  214.             readLine((char *)cmd);
  215.         }
  216.         if (strstr("qQxX", cmd) != NULL && strlen(cmd) == 1) {
  217.             exit(0);
  218.         }
  219.         else if (strstr("aA", cmd) != NULL && strlen(cmd) == 1) {
  220.             printAbout();
  221.         }
  222.         else if (strstr("sS", cmd) != NULL && strlen(cmd) == 1) {
  223.             print("  Input the source and target radices (say, 16 2): ");
  224.             readTwo((struct _TOKEN *) &st);
  225.             srcRadix = convertAtoI(st.a, 10);
  226.             destRadix = convertAtoI(st.b, 10);
  227.             doConvert(srcRadix, destRadix);
  228.         }
  229.     } while (TRUE);
  230. }
  231. void main(int argc, char *argv[]) {
  232.     if (argc > 1 && strcmp("-h", argv[1]) == 0) {
  233.         printUsage();
  234.         exit(1);
  235.     }
  236.     doStart();
  237. }




컴파일> cl convertRadix.c

실행> convertRadix

  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): 8 16

    Convert Radix_8 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1234
        ( 1234 )_8   --->   ( 29C )_16

    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): 16 8

    Convert Radix_16 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 29c
        ( 29c )_16   --->   ( 1234 )_8

    Input Value>> exit()



Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Lua 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Lua 의 빌트인 함수 tonumber(string, radix)와 소스 코드에 자체 작성된 함수 itoa(number, radix)의 사용이다.

         val = tonumber(s, srcRdx)
         ret = itoa(val, destRdx)

지원되는 진법은 2진법에서 36진법 까지이다.



  1. --  Filename: convertRadix.lua
  2. --            Convert radix in a interactive mode.
  3. --
  4. --   Execute: lua convertRadix.lua
  5. --
  6. --      Date:  2008/03/26
  7. --    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. function println(s)
  9.     if s ~= nil then
  10.         print(s)
  11.     else
  12.         print("")
  13.     end
  14. end
  15. function printUsage()
  16.     println("Usage: lua convertRadix.lua")
  17.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  18. end
  19. function printAbout()
  20.     println("    About: Convert radix in a interactive mode.")
  21. end
  22. function printMainMenu()
  23.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  24. end
  25. function printMainPrompt()
  26.     io.write("  Prompt> ")
  27. end
  28. function printSubMenu(srcRadix, destRadix)
  29.     println("    Convert Radix_" .. srcRadix .. " to Radix_" .. destRadix)
  30.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  31. end
  32. function printSubPrompt()
  33.     io.write("    Input Value>> ")
  34. end
  35. local BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36. function itoa(num, radix)
  37.    local isNegative = false
  38.    if num < 0 then
  39.       isNegative = true
  40.       num = -num
  41.    end
  42.    local arr = {}
  43.    local q, r = num, 0
  44.    while q >= radix do
  45.       r = math.fmod(q, radix)
  46.       q = math.floor(q / radix)
  47.       table.insert(arr, string.sub(BASE36, r+1, r+1))
  48.    end
  49.    table.insert(arr, string.sub(BASE36, q+1, q+1))
  50.    if isNegative then
  51.       table.insert(arr, "-")
  52.    end
  53.    local ret = ""
  54.    for i = #arr, 1, -1 do
  55.        ret = ret .. arr[i]
  56.    end
  57.    return ret
  58. end
  59. function convertRadix(s, srcRdx, destRdx)
  60.     local val = tonumber(s, srcRdx)
  61.     local ret = itoa(val, destRdx)
  62.     return string.upper(ret)
  63. end
  64. function doConvert(srcRadix, destRadix)
  65.     local line = ""
  66.     local cmd = ""
  67.     local srcStr = ""
  68.     local destStr = ""
  69.     printSubMenu(srcRadix, destRadix)
  70.     while true do
  71.         printSubPrompt()
  72.         cmd = io.read()
  73.         while string.len(cmd) < 1 do
  74.             cmd = io.read()
  75.         end
  76.         if "main()" == cmd then
  77.             return
  78.         elseif "exit()" == cmd or "quit()" == cmd then
  79.             os.exit(0)
  80.         end
  81.         local flagContinue = true
  82.         if tonumber(cmd, srcRadix) == nil then
  83.             flagContinue = false
  84.         end
  85.         if flagContinue then
  86.             srcStr = cmd
  87.             destStr = convertRadix(srcStr, srcRadix, destRadix)
  88.             println("        ( " .. srcStr .. " )_" .. srcRadix .. "   --->   ( " .. destStr .. " )_" .. destRadix)
  89.             println("")
  90.         end
  91.     end
  92. end
  93. function doStart()
  94.     local line = ""
  95.     local cmd = ""
  96.     local srcRadix = 10
  97.     local destRadix = 10
  98.     local srcStr = ""
  99.     local destStr = ""
  100.     local onlyOnce = true
  101.     while true do
  102.         println()
  103.         if onlyOnce then
  104.             println("  The supported maximum radix is 36.")
  105.             onlyOnce = false
  106.         end
  107.         printMainMenu()
  108.         printMainPrompt()
  109.         cmd = io.read()
  110.         while string.len(cmd) < 1 do
  111.             cmd = io.read()
  112.         end
  113.         if string.find("qQxX", cmd) ~= nil and string.len(cmd) == 1 then
  114.             os.exit(0)
  115.         elseif string.find("aA", cmd) ~= nil and string.len(cmd) == 1 then
  116.             printAbout()
  117.         elseif string.find("sS", cmd) ~= nil and string.len(cmd) == 1 then
  118.             io.write("  Input the source and target radices (say, 16 2): ")
  119.             line = io.read()
  120.             while string.len(line) < 1 do
  121.                 line = io.read()
  122.             end
  123.             st = {}
  124.             for w in string.gmatch(line, "[0-9]*") do
  125.                 if string.len(w) > 0 then
  126.                     table.insert(st, w)
  127.                 end
  128.             end
  129.             while #st < 2 do
  130.                 io.write("  Input the source and target radices (say, 16 2): ")
  131.                 line = io.read()
  132.                while string.len(line) < 1 do
  133.                     line = io.read()
  134.                 end
  135.                 st = {}
  136.                 for w in string.gmatch(line, "%a+") do
  137.                     if string.len(w) > 0 then
  138.                         table.insert(st, w)
  139.                     end
  140.                 end
  141.             end
  142.             println("")
  143.             srcRadix = tonumber(st[1])
  144.             destRadix = tonumber(st[2])
  145.             doConvert(srcRadix, destRadix)
  146.         end
  147.     end
  148. end
  149. -- Begin here
  150. if #arg > 0 and "-h" == arg[1] then
  151.     printUsage()
  152.     os.exit(1)
  153. end
  154. doStart()




실행> lua convertRadix.lua

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 2

    Convert Radix_16 to Radix_2
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 7F
        ( 7F )_16   --->   ( 1111111 )_2

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> S
  Input the source and target radices (say, 16 2): 2 16

    Convert Radix_2 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1111111
        ( 1111111 )_2   --->   ( 7F )_16

    Input Value>> exit()





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Ruby 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Ruby의 string 클래스의 빌트인(build-in) 함수 string.to_i(radix)와 소스 코드에 자체 작성된 함수 itoa(number, radix)의 사용이다.

         val = s.to_i(srcRdx)
         ret = itoa(val, destRdx)

지원되는 진법은 2진법에서 36진법 까지이다.
(JRuby로는 gets 때문에 실행되지 않는다.)



  1. #  Filename: convertRadix.rb
  2. #            Convert radix in a interactive mode.
  3. #
  4. #  Execute: ruby convertRadix.rb
  5. #
  6. #      Date:  2008/03/26
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. def println(s=nil)
  9.     if s != nil
  10.         print("%s\n" % s)
  11.     else
  12.         print("\n")
  13.     end
  14. end
  15. def printUsage()
  16.     println("Usage: ruby convertRadix.rb")
  17.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  18. end
  19. def printAbout()
  20.     println("    About: Convert radix in a interactive mode.")
  21. end
  22. def printMainMenu()
  23.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  24. end
  25. def printMainPrompt()
  26.     print("  Prompt> ")
  27. end
  28. def printSubMenu(srcRadix, destRadix)
  29.     println("    Convert Radix_" + srcRadix.to_s + " to Radix_" + destRadix.to_s)
  30.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  31. end
  32. def printSubPrompt()
  33.     print("    Input Value>> ")
  34. end
  35. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36. def itoa(num, radix=10)
  37.    isNegative = false
  38.    if num < 0
  39.       isNegative = true
  40.       num = -num
  41.    end
  42.    arr = []
  43.    q, r = num, 0
  44.    while q >= radix
  45.       val = q.divmod(radix)
  46.       q, r = val[0], val[1]
  47.       arr.push(BASE36.slice(r..r))
  48.    end
  49.    arr.push(BASE36.slice(q..q))
  50.    if isNegative
  51.       arr.push("-")
  52.    end
  53.    b = arr.reverse()
  54.    return b.join
  55. end
  56. def convertRadix(s, srcRdx, destRdx)
  57.     ret = ""
  58.     begin
  59.         val = s.to_i(srcRdx)
  60.         ret = itoa(val, destRdx)
  61. return ret.upcase
  62.     rescue
  63.         println("    Error: Cannot convert radix " + str(srcRdx))
  64.         ret = "????"
  65.     end
  66. end
  67. def doConvert(srcRadix, destRadix)
  68.     line = ""
  69.     cmd = ""
  70.     srcStr = ""
  71.     destStr = ""
  72.     println("")
  73.     printSubMenu(srcRadix, destRadix)
  74.     begin
  75.         while true
  76.             printSubPrompt()
  77.             cmd = gets
  78.             while cmd.length < 2
  79.                 cmd = gets
  80.             end
  81.             cmd = cmd[0...cmd.length-1]
  82.             if "main()" == cmd
  83.                 return
  84.             elsif "exit()" == cmd or "quit()" == cmd
  85.                 exit(0)
  86.             end
  87.             begin
  88.                 cmd.to_i(srcRadix)
  89.                 srcStr = cmd
  90.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  91.                 println("        ( " + srcStr + " )_" + srcRadix.to_s +  "   --->   ( " + destStr + " )_" + destRadix.to_s)
  92.                 println("")
  93.             rescue
  94.                  nil
  95.             end
  96.         end
  97.     rescue
  98.         puts "    An error occurred: #{$!}"
  99.         retry
  100.     end
  101. end
  102. def doStart()
  103.     line = ""
  104.     cmd = ""
  105.     srcRadix = 10
  106.     destRadix = 10
  107.     srcStr = ""
  108.     destStr = ""
  109.     onlyOnce = true
  110.     begin
  111.         while true
  112.             println()
  113.             if onlyOnce
  114.                 println("  The supported maximum radix is 36.")
  115.                 onlyOnce = false
  116.             end
  117.             printMainMenu()
  118.             printMainPrompt()
  119.             cmd = gets
  120.             while cmd.length < 1
  121.                 cmd = gets
  122.             end
  123.             cmd = cmd[0...cmd.length-1]
  124.             if "qQxX".include?(cmd) and cmd.length == 1
  125.                 exit(0)
  126.             elsif "aA".include?(cmd) and cmd.length == 1
  127.                 printAbout()
  128.             elsif "sS".include?(cmd) and cmd.length == 1
  129.                 print("  Input the source and target radices (say, 16 2): ")
  130.                 line = gets
  131.                 line = line[0...line.length-1]
  132.                 st = line.split(" ")
  133.                 while st.length < 2
  134.                     print("  Input the source and target radices (say, 16 2): ")
  135.                     line = gets
  136.                     line = line[0...line.length-1]
  137.                     st = line.split(" ")
  138.                 end
  139.                 srcRadix = st[0].to_i
  140.                 destRadix = st[1].to_i
  141.                 doConvert(srcRadix, destRadix)
  142.             end
  143.         end
  144.     rescue
  145.         puts "  An error occurred: #{$!}"
  146.         retry
  147.     end
  148. end
  149. # Begin here
  150. if ARGV.length > 0 and "-h" == ARGV[0]
  151.     printUsage()
  152.     exit(1)
  153. end
  154. doStart()




실행> ruby convertRadix.rb

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 8 2

    Convert Radix_8 to Radix_2
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 123
        ( 123 )_8   --->   ( 1010011 )_2

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 2 8

    Convert Radix_2 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1010011
        ( 1010011 )_2   --->   ( 123 )_8

    Input Value>> quit()




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Python 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Python의 빌트인 함수 int(string, radix)와 소스 코드에 자체 작성된 함수 itoa(number, radix)의 사용이다.

         val = int(s, srcRdx)
         ret = itoa(val, destRdx)

지원되는 진법은 2진법에서 36진법까지이다.
(Jython으로는 finally: 구문 때문에 실행이 안된다.)



  1. #  Filename: convertRadix.py
  2. #            Convert radix in a interactive mode.
  3. #
  4. #  Execute: python convertRadix.py
  5. #
  6. #      Date:  2008/03/25
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import sys
  9. def println(s=None):
  10.     if s != None:
  11.         print(s)
  12.     else:
  13.         print
  14. def printUsage():
  15.     println("Usage: python convertRadix.py")
  16.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  17. def printAbout():
  18.     println("    About: Convert radix in a interactive mode.")
  19. def printMainMenu():
  20.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  21. def printMainPrompt():
  22.     print("  Prompt>"),
  23. def printSubMenu(srcRadix, destRadix):
  24.     println("    Convert Radix_" + str(srcRadix) + " to Radix_" + str(destRadix))
  25.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  26. def printSubPrompt():
  27.     print("    Input Value>>"),
  28. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  29. def itoa(num, radix=10):
  30.    isNegative = False
  31.    if num < 0:
  32.       isNegative = True
  33.       num = -num
  34.    arr = []
  35.    q, r = num, 0
  36.    while q >= radix:
  37.       q, r = divmod(q, radix)
  38.       arr.append(BASE36[r])
  39.    arr.append(BASE36[q])
  40.    if isNegative:
  41.       arr.append("-")
  42.    arr.reverse()
  43.    return ''.join(arr)
  44. def convertRadix(s, srcRdx, destRdx):
  45.     ret = ""
  46.     try:
  47.         val = int(s, srcRdx)
  48.         ret = itoa(val, destRdx)
  49.         return ret.upper()
  50.     except ValueError:
  51.         println("    Error: Cannot convert radix " + str(srcRdx))
  52.         ret = "????"
  53.     finally:
  54.         return ret.upper()
  55. def doConvert(srcRadix, destRadix):
  56.     line = ""
  57.     cmd = ""
  58.     srcStr = ""
  59.     destStr = ""
  60.     println("")
  61.     printSubMenu(srcRadix, destRadix)
  62.     try:
  63.         while True:
  64.             printSubPrompt()
  65.             cmd = raw_input()
  66.             while cmd == None:
  67.                 cmd = raw_input()
  68.             if "main()" == cmd:
  69.                 return
  70.             elif "exit()" == cmd or "quit()" == cmd:
  71.                 sys.exit(0)
  72.             try:
  73.                 int(cmd, srcRadix)
  74.                 srcStr = cmd
  75.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  76.                 println("        ( " + srcStr + " )_" + str(srcRadix) +  "   --->   ( " + destStr + " )_" + str(destRadix))
  77.                 println("")
  78.             except ValueError:
  79.                  pass
  80.     except RuntimeError:
  81.         print sys.exc_value
  82. def doStart():
  83.     line = ""
  84.     cmd = ""
  85.     srcRadix = 10
  86.     destRadix = 10
  87.     srcStr = ""
  88.     destStr = ""
  89.     onlyOnce = True
  90.     try:
  91.         while True:
  92.             println()
  93.             if onlyOnce:
  94.                 println("  The supported maximum radix is 36.")
  95.                 onlyOnce = False
  96.             printMainMenu()
  97.             printMainPrompt()
  98.             cmd = raw_input()
  99.             while cmd == None:
  100.                 cmd = raw_input()
  101.             if "qQxX".find(cmd) >= 0 and len(cmd) == 1:
  102.                 sys.exit(0)
  103.             elif "aA".find(cmd) >= 0 and len(cmd) == 1:
  104.                 printAbout()
  105.             elif "sS".find(cmd) >= 0 and len(cmd) == 1:
  106.                 line = raw_input("  Input the source and target radices (say, 16 2): ")
  107.                 st = line.split(" ")
  108.                 while len(st) < 2:
  109.                     line = raw_input("  Input the source and target radices (say, 16 2): ")
  110.                     st = line.split(" ")
  111.                 srcRadix = int(st[0])
  112.                 destRadix = int(st[1])
  113.                 doConvert(srcRadix, destRadix)
  114.     except RuntimeError:
  115.         print sys.exc_value
  116. # Begin here
  117. if len(sys.argv) > 1 and "-h" == sys.argv[1]:
  118.     printUsage()
  119.     sys.exit(1)
  120. doStart()



실행> python convertRadix.py

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 8

    Convert Radix_10 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 200
        ( 200 )_10   --->   ( 310 )_8

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> S
  Input the source and target radices (say, 16 2): 8 10

    Convert Radix_8 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 2666
        ( 2666 )_8   --->   ( 1462 )_10

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> x




IronPython의 경우에는 구문

    print 스트링,

이 Python과 달리 끝에 빈칸을 곧 바로 추가하지 않고, 빈칸 출력을 유보하고 있다가 다음 print 문을 만날 때 이 빈칸을 먼저 출력한 후 주어진 스트링을 출력한다. raw_input()과 함께 쓰일 때는 이 빈칸 하나 때문에 신경이 쓰이기도 한다. 그래서 프롬프트를 출력하는 함수를

def printMainPrompt(): 
     print("  Prompt> "),

def printSubPrompt(): 
     print("    Input Value>> "),

로 수정해야 한다.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Groovy 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Integer 클래스와 Long 클래스의 정적 메소드

         Integer.parseInt(String, int);
         Long.toString(long, int);

울 이용하였으며, 지원되는 진법은 2진법에서 36진법 까지이다.



  1. /*
  2.  *  Filename: convertRadix.groovy
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Execute: groovy convertRadix.groovy
  6.  *
  7.  *      Date:  2008/03/25
  8.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  9.  */
  10. import java.io.*
  11. def printUsage() {
  12.     println("Usage: groovy convertRadix.groovy")
  13.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  14. }
  15. def printAbout() {
  16.     println("    About: Convert radix in a interactive mode.")
  17. }
  18. def printMainMenu() {
  19.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  20. }
  21. def printMainPrompt() {
  22.     print("  Prompt> ")
  23. }
  24. def printSubMenu(int srcRadix, int destRadix) {
  25.     println("    Convert Radix_" + srcRadix + " to Radix_" + destRadix)
  26.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  27. }
  28. def printSubPrompt() {
  29.     print("    Input Value>> ")
  30. }
  31. String convertRadix(String s,  int srcRdx, int destRdx) {
  32.     long val
  33.     String ret = ""
  34.     try {
  35.         val = Integer.parseInt(s, srcRdx)
  36.         ret = Long.toString(val, destRdx)
  37.         return ret.toUpperCase()
  38.     }
  39.     catch (NumberFormatException nfx) {
  40.         println("    Error: " + nfx.getMessage() + " cantains some invalid character.")
  41.         ret = "????"
  42.     }
  43.     finally {
  44.       return ret.toUpperCase()
  45.     }
  46. }
  47. def doConvert(BufferedReader r, int srcRadix, int destRadix) {
  48.     def line
  49.     def cmd
  50.     def srcStr = "", destStr = ""
  51.     println()
  52.     printSubMenu(srcRadix, destRadix)
  53.     try {
  54.         while (true) {
  55.             printSubPrompt()
  56.             while ((cmd = r.readLine()) == null) {
  57.             }
  58.             if ("main()".equals(cmd)) {
  59.                 return
  60.             }
  61.             else if ("exit()".equals(cmd) || "quit()".equals(cmd)) {
  62.                 System.exit(0)
  63.             }
  64.             try {
  65.                 Integer.parseInt(cmd, srcRadix)
  66.                 srcStr = cmd
  67.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  68.                 println("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix)
  69.                 println()
  70.             }
  71.             catch (NumberFormatException nfx) {
  72.             }
  73.         }
  74.     }
  75.     catch (IOException ex) {
  76.         ex.printStackTrace()
  77.     }
  78. }
  79. def doStart() {
  80.     def line
  81.     def cmd
  82.     def srcRadix = 10, destRadix = 10
  83.     def srcStr = "", destStr = ""
  84.     boolean onlyOnce = true
  85.     BufferedReader r = new BufferedReader(new InputStreamReader(System.in))
  86.     try {
  87.         while (true) {
  88.             println()
  89.             if (onlyOnce) {
  90.                 println("  The supported maximum radix is 36.")
  91.                 onlyOnce = false
  92.             }
  93.             printMainMenu()
  94.             printMainPrompt()
  95.             while ((cmd = r.readLine()) == null) {
  96.             }
  97.             if ("qQxX".contains(cmd) && cmd.length() == 1) {
  98.                 System.exit(0)
  99.             }
  100.             else if ("aA".contains(cmd) && cmd.length() == 1) {
  101.                 printAbout()
  102.             }
  103.             else if ("sS".contains(cmd) && cmd.length() == 1) {
  104.                 print("  Input the source and target radices (say, 16 2): ")
  105.                 line = r.readLine()
  106.                 StringTokenizer st = new StringTokenizer(line, " ,\t")
  107.                 while (st.countTokens() < 2) {
  108.                     print("  Input the source and target radices (say, 16 2): ")
  109.                     line = r.readLine()
  110.                     st = new StringTokenizer(line, " ,\t");
  111.                 }
  112.                 srcRadix = Integer.parseInt(st.nextToken())
  113.                 destRadix = Integer.parseInt(st.nextToken())
  114.                 doConvert(r, srcRadix, destRadix)
  115.             }
  116.         }
  117.     }
  118.     catch (IOException ex) {
  119.         ex.printStackTrace()
  120.     }
  121. }
  122. // Begin here
  123. if (args.length > 0 && "-h".equals(args[0])) {
  124.     printUsage()
  125.     System.exit(1)
  126. }
  127. doStart()



실행> groovy convertRadix.groovy

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 2

    Convert Radix_16 to Radix_2
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1FF
        ( 1FF )_16   --->   ( 111111111 )_2

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> S
  Input the source and target radices (say, 16 2): 2 8

    Convert Radix_2 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1011001
        ( 1011001 )_2   --->   ( 131 )_8

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> x




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,