다음은 대화형 모드(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 때문에 실행되지 않는다.)
- # Filename: convertRadix.rb
- # Convert radix in a interactive mode.
- #
- # Execute: ruby convertRadix.rb
- #
- # Date: 2008/03/26
- # Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- def println(s=nil)
- if s != nil
- print("%s\n" % s)
- else
- print("\n")
- end
- end
- def printUsage()
- println("Usage: ruby convertRadix.rb")
- println("Convert radix in a interactive mode, where the maximum radix is 36.")
- end
- def printAbout()
- println(" About: Convert radix in a interactive mode.")
- end
- def printMainMenu()
- println(" Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
- end
- def printMainPrompt()
- print(" Prompt> ")
- end
- def printSubMenu(srcRadix, destRadix)
- println(" Convert Radix_" + srcRadix.to_s + " to Radix_" + destRadix.to_s)
- println(" SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
- end
- def printSubPrompt()
- print(" Input Value>> ")
- end
- BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- def itoa(num, radix=10)
- isNegative = false
- if num < 0
- isNegative = true
- num = -num
- end
- arr = []
- q, r = num, 0
- while q >= radix
- val = q.divmod(radix)
- q, r = val[0], val[1]
- arr.push(BASE36.slice(r..r))
- end
- arr.push(BASE36.slice(q..q))
- if isNegative
- arr.push("-")
- end
- b = arr.reverse()
- return b.join
- end
- def convertRadix(s, srcRdx, destRdx)
- ret = ""
- begin
- val = s.to_i(srcRdx)
- ret = itoa(val, destRdx)
- return ret.upcase
- rescue
- println(" Error: Cannot convert radix " + str(srcRdx))
- ret = "????"
- end
- end
- def doConvert(srcRadix, destRadix)
- line = ""
- cmd = ""
- srcStr = ""
- destStr = ""
- println("")
- printSubMenu(srcRadix, destRadix)
- begin
- while true
- printSubPrompt()
- cmd = gets
- while cmd.length < 2
- cmd = gets
- end
- cmd = cmd[0...cmd.length-1]
- if "main()" == cmd
- return
- elsif "exit()" == cmd or "quit()" == cmd
- exit(0)
- end
- begin
- cmd.to_i(srcRadix)
- srcStr = cmd
- destStr = convertRadix(srcStr, srcRadix, destRadix)
- println(" ( " + srcStr + " )_" + srcRadix.to_s + " ---> ( " + destStr + " )_" + destRadix.to_s)
- println("")
- rescue
- nil
- end
- end
- rescue
- puts " An error occurred: #{$!}"
- retry
- end
- end
- def doStart()
- line = ""
- cmd = ""
- srcRadix = 10
- destRadix = 10
- srcStr = ""
- destStr = ""
- onlyOnce = true
- begin
- while true
- println()
- if onlyOnce
- println(" The supported maximum radix is 36.")
- onlyOnce = false
- end
- printMainMenu()
- printMainPrompt()
- cmd = gets
- while cmd.length < 1
- cmd = gets
- end
- cmd = cmd[0...cmd.length-1]
- if "qQxX".include?(cmd) and cmd.length == 1
- exit(0)
- elsif "aA".include?(cmd) and cmd.length == 1
- printAbout()
- elsif "sS".include?(cmd) and cmd.length == 1
- print(" Input the source and target radices (say, 16 2): ")
- line = gets
- line = line[0...line.length-1]
- st = line.split(" ")
- while st.length < 2
- print(" Input the source and target radices (say, 16 2): ")
- line = gets
- line = line[0...line.length-1]
- st = line.split(" ")
- end
- srcRadix = st[0].to_i
- destRadix = st[1].to_i
- doConvert(srcRadix, destRadix)
- end
- end
- rescue
- puts " An error occurred: #{$!}"
- retry
- end
- end
- # Begin here
- if ARGV.length > 0 and "-h" == ARGV[0]
- printUsage()
- exit(1)
- end
- 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()
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
'프로그래밍 > Ruby' 카테고리의 다른 글
7비트 ASCII 코드표 만들기 예제 with Ruby (0) | 2008.03.31 |
---|---|
진법(radix) 표 만들기 예제 with Ruby (0) | 2008.03.29 |
황금비율(golden ratio) 구하기 with Ruby or JRuby (0) | 2008.03.24 |
현재 시각 알아내기 for Ruby and JRuby (0) | 2008.03.24 |
조립제법(Horner의 방법) 예제 for Ruby (0) | 2008.03.14 |