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

         val as long = convertAtoI(s, srcRdx)
         ret = itoa(val, destRdx)

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

 또 스트링의 첫글자의 아스키(ascii) 코드값을 구해주는 함수 toAscii(스트링을) 자체 구현하여 사용하였다. 이 함수는 convertAtoI(스트링, radix)에서 (Python의 함수 ord(스트링) 대신) 사용되고 있다.


  1. #  Filename: convertRadix.boo
  2. #            Convert radix in a interactive mode.
  3. #
  4. #  Execute: booi convertRadix.boo
  5. #
  6. #      Date:  2009/04/03
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import System
  9. def println():
  10.     print
  11. def println(s):
  12.     print(s)
  13. def printUsage():
  14.     println("Usage: booi convertRadix.boo")
  15.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  16. def printAbout():
  17.     println("    About: Convert radix in a interactive mode.")
  18. def printMainMenu():
  19.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  20. def printMainPrompt():
  21.     Console.Write("  Prompt> ")
  22. def printSubMenu(srcRadix, destRadix):
  23.     println("    Convert Radix_" + srcRadix + " to Radix_" + destRadix)
  24.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  25. def printSubPrompt(): 
  26.     Console.Write("    Input Value>> ")
  27. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  28. def itoa(num as long, radix as int):
  29.    isNegative = false
  30.    if num < 0:
  31.       isNegative = true
  32.       num = -num
  33.    arr as List = []
  34.    q as int = num
  35.    r as int = 0
  36.    while q >= radix:
  37.       r = q % radix
  38.       q = q / radix
  39.       arr.Add(BASE36[r])
  40.    arr.Add(BASE36[q])
  41.    if isNegative:
  42.       arr.Add("-")
  43.    s as string = ""
  44.    n = len(arr)
  45.    for i as int in range(n):
  46.        s += arr[n - 1 - i]
  47.    return s
  48. def toAscii(s as String) as int:
  49.     objAscii as System.Text.ASCIIEncoding = System.Text.ASCIIEncoding()
  50.     val as System.Byte = objAscii.GetBytes(s)[0]
  51.     return Convert.ToInt32(val)
  52. def convertAtoI(srcStr as string, radix as int) as long:
  53.     isNegative = false
  54.     ret as long = 0L
  55.     m = len(srcStr)
  56.     val = 0
  57.     c = srcStr[0:1]
  58.     if toAscii(c) == toAscii('-'):
  59.         isNegative = true
  60.     elif toAscii(c) >= toAscii('0') and toAscii(c) <= toAscii('9'):
  61.         ret = toAscii(c) - toAscii('0')
  62.     elif toAscii(c) >= toAscii('A') and toAscii(c) <= toAscii('Z'):
  63.         ret = (toAscii(c) - toAscii('A')) + 10
  64.     elif toAscii(c) >= toAscii('a') and toAscii(c) <= toAscii('z'):
  65.         ret = (toAscii(c) - toAscii('a')) + 10
  66.     if ret >= radix:
  67.         raise Exception("        invalid character!")
  68.         return ret
  69.     for i in range(1, m):
  70.         c = srcStr[i:i+1]
  71.         ret *= radix
  72.         if toAscii(c) >= char('0') and toAscii(c) <= char('9'):
  73.             val = toAscii(c) - toAscii('0')
  74.         elif toAscii(c) >= char('A') and toAscii(c) <= char('Z'):
  75.             val = (toAscii(c) - toAscii('A')) + 10
  76.         elif toAscii(c) >= char('a') and toAscii(c) <= char('z'):
  77.             val = (toAscii(c) - toAscii('a')) + 10
  78.         if val >= radix:
  79.             raise Exception("        invalid character!")
  80.             return ret
  81.         ret += val
  82.     return ret
  83. def convertRadix(s, srcRdx as int, destRdx as int) as string:
  84.     ret as string = ""
  85.     try:
  86.         val as long = convertAtoI(s, srcRdx)
  87.         ret = itoa(val, destRdx)
  88.         return ret.ToUpper()
  89.     except errMsg:
  90.         print(errMsg + "\n    Error: Cannot convert radix " + srcRdx)
  91.         ret = "????"
  92.     ensure:
  93.         pass
  94.     return ret.ToUpper()
  95. def doConvert(srcRadix as int, destRadix as int):
  96.     line = ""
  97.     cmd = ""
  98.     srcStr = ""
  99.     destStr = ""
  100.     println("")
  101.     printSubMenu(srcRadix, destRadix)
  102.     try:
  103.         while true:
  104.             printSubPrompt()
  105.             cmd = gets()
  106.             if "main()" == cmd:
  107.                 return
  108.             elif "exit()" == cmd or "quit()" == cmd:
  109.                 Environment.Exit(0)
  110.             try:
  111.                 srcStr = cmd
  112.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  113.                 println("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix)
  114.                 println("")
  115.             except ValueError:
  116.                  pass
  117.     except RuntimeError:
  118.         print "Number Format Error"
  119. def doStart():
  120.     line = ""
  121.     cmd = ""
  122.     srcRadix as int = 10
  123.     destRadix as int = 10
  124.     srcStr = ""
  125.     destStr = ""
  126.     onlyOnce = true
  127.     try:
  128.         while true:
  129.             println()
  130.             if onlyOnce:
  131.                 println("  The supported maximum radix is 36.")
  132.                 onlyOnce = false
  133.             printMainMenu()
  134.             printMainPrompt()
  135.             cmd = gets()
  136.             if "qQxX".IndexOf(cmd) >= 0 and len(cmd) == 1:
  137.                 Environment.Exit(0)
  138.             elif "aA".IndexOf(cmd) >= 0 and len(cmd) == 1:
  139.                 printAbout()
  140.             elif "sS".IndexOf(cmd) >= 0 and len(cmd) == 1:
  141.                 line = prompt("  Input the source and target radices (say, 16 2): ")
  142.                 st = @/\s/.Split(line)
  143.                 while len(st) < 2:
  144.                     line = prompt("  Input the source and target radices (say, 16 2): ")
  145.                     st = @/\s/.Split(line)
  146.                 srcRadix = Convert.ToInt32(st[0])
  147.                 destRadix = Convert.ToInt32(st[1])
  148.                 doConvert(srcRadix, destRadix)
  149.     except RuntimeError:
  150.         print "Number Format Error"
  151. # Begin here
  152. if len(argv) > 0 and "-h" == argv[0]:
  153.     printUsage()
  154.     Environment.Exit(1)
  155. doStart()



실행> booi convertRadix.boo

  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




크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,