다음은 대화형 모드(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(스트링) 대신) 사용되고 있다.
- # Filename: convertRadix.boo
- # Convert radix in a interactive mode.
- #
- # Execute: booi convertRadix.boo
- #
- # Date: 2009/04/03
- # Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- import System
- def println():
- def println(s):
- print(s)
- def printUsage():
- println("Usage: booi convertRadix.boo")
- println("Convert radix in a interactive mode, where the maximum radix is 36.")
- def printAbout():
- println(" About: Convert radix in a interactive mode.")
- def printMainMenu():
- println(" Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
- def printMainPrompt():
- Console.Write(" Prompt> ")
- def printSubMenu(srcRadix, destRadix):
- println(" Convert Radix_" + srcRadix + " to Radix_" + destRadix)
- println(" SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
- def printSubPrompt():
- Console.Write(" Input Value>> ")
- BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- def itoa(num as long, radix as int):
- isNegative = false
- if num < 0:
- isNegative = true
- num = -num
- arr as List = []
- q as int = num
- r as int = 0
- while q >= radix:
- r = q % radix
- q = q / radix
- arr.Add(BASE36[r])
- arr.Add(BASE36[q])
- if isNegative:
- arr.Add("-")
- s as string = ""
- n = len(arr)
- for i as int in range(n):
- s += arr[n - 1 - i]
- return s
- def toAscii(s as String) as int:
- objAscii as System.Text.ASCIIEncoding = System.Text.ASCIIEncoding()
- val as System.Byte = objAscii.GetBytes(s)[0]
- return Convert.ToInt32(val)
- def convertAtoI(srcStr as string, radix as int) as long:
- isNegative = false
- ret as long = 0L
- m = len(srcStr)
- val = 0
- c = srcStr[0:1]
- if toAscii(c) == toAscii('-'):
- isNegative = true
- elif toAscii(c) >= toAscii('0') and toAscii(c) <= toAscii('9'):
- ret = toAscii(c) - toAscii('0')
- elif toAscii(c) >= toAscii('A') and toAscii(c) <= toAscii('Z'):
- ret = (toAscii(c) - toAscii('A')) + 10
- elif toAscii(c) >= toAscii('a') and toAscii(c) <= toAscii('z'):
- ret = (toAscii(c) - toAscii('a')) + 10
- if ret >= radix:
- raise Exception(" invalid character!")
- return ret
- for i in range(1, m):
- c = srcStr[i:i+1]
- ret *= radix
- if toAscii(c) >= char('0') and toAscii(c) <= char('9'):
- val = toAscii(c) - toAscii('0')
- elif toAscii(c) >= char('A') and toAscii(c) <= char('Z'):
- val = (toAscii(c) - toAscii('A')) + 10
- elif toAscii(c) >= char('a') and toAscii(c) <= char('z'):
- val = (toAscii(c) - toAscii('a')) + 10
- if val >= radix:
- raise Exception(" invalid character!")
- return ret
- ret += val
- return ret
- def convertRadix(s, srcRdx as int, destRdx as int) as string:
- ret as string = ""
- try:
- val as long = convertAtoI(s, srcRdx)
- ret = itoa(val, destRdx)
- return ret.ToUpper()
- except errMsg:
- print(errMsg + "\n Error: Cannot convert radix " + srcRdx)
- ret = "????"
- ensure:
- pass
- return ret.ToUpper()
- def doConvert(srcRadix as int, destRadix as int):
- line = ""
- cmd = ""
- srcStr = ""
- destStr = ""
- println("")
- printSubMenu(srcRadix, destRadix)
- try:
- while true:
- printSubPrompt()
- cmd = gets()
- if "main()" == cmd:
- return
- elif "exit()" == cmd or "quit()" == cmd:
- Environment.Exit(0)
- try:
- srcStr = cmd
- destStr = convertRadix(srcStr, srcRadix, destRadix)
- println(" ( " + srcStr + " )_" + srcRadix + " ---> ( " + destStr + " )_" + destRadix)
- println("")
- except ValueError:
- pass
- except RuntimeError:
- print "Number Format Error"
- def doStart():
- line = ""
- cmd = ""
- srcRadix as int = 10
- destRadix as int = 10
- srcStr = ""
- destStr = ""
- onlyOnce = true
- try:
- while true:
- println()
- if onlyOnce:
- println(" The supported maximum radix is 36.")
- onlyOnce = false
- printMainMenu()
- printMainPrompt()
- cmd = gets()
- if "qQxX".IndexOf(cmd) >= 0 and len(cmd) == 1:
- Environment.Exit(0)
- elif "aA".IndexOf(cmd) >= 0 and len(cmd) == 1:
- printAbout()
- elif "sS".IndexOf(cmd) >= 0 and len(cmd) == 1:
- line = prompt(" Input the source and target radices (say, 16 2): ")
- st = @/\s/.Split(line)
- while len(st) < 2:
- line = prompt(" Input the source and target radices (say, 16 2): ")
- st = @/\s/.Split(line)
- srcRadix = Convert.ToInt32(st[0])
- destRadix = Convert.ToInt32(st[1])
- doConvert(srcRadix, destRadix)
- except RuntimeError:
- print "Number Format Error"
- # Begin here
- if len(argv) > 0 and "-h" == argv[0]:
- printUsage()
- Environment.Exit(1)
- 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
'프로그래밍 > Boo' 카테고리의 다른 글
7비트 ASCII 코드표 만들기 예제 with Boo (0) | 2009.04.03 |
---|---|
진법(radix) 표 만들기 예제 with Boo (0) | 2009.04.03 |
황금비율(golden ratio) 구하기 with Boo (0) | 2009.04.01 |
현재 시각 알아내기 for Boo (0) | 2009.04.01 |
손으로 만드는 나눗셈 계산표 with Boo (0) | 2009.04.01 |