다음은  대화형 모드(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
,