다음은 대화형 모드(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
로 구성되어 있으며, 진법 변환의 핵심은
public static long ConvertAtoI(string s, int radix)
public static string ConvertItoA(long num, int radix)
의 구현과 이용이다. 지원되는 진법은 2진법부터 36진법까지이다.
C#에는 Java의 StringTokener가 구현되어 있지 않다.
그래서 Java의 StringTokener와 비슷한 C#용 StringTokener.Token이라는
클래스를 구현해 보았다.
- /*
- * Filename: ConvertRadixApp.cs
- * Convert radix in a interactive mode.
- *
- * Compile: csc ConvertRadixApp.cs
- * Execute: ConvertRadixApp
- *
- * Date: 2009/01/19
- * Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- */
- using System;
- namespace StringTokenizer {
- class Token {
- private string data,delimeter;
- private string[] tokens;
- private int index;
- public Token(string strdata) {
- Init(strdata, " ");
- }
- public Token(string strdata, string delim) {
- Init(strdata, delim);
- }
- private void Init(string strdata, string delim) {
- data = strdata;
- delimeter = delim;
- string data2 = "";
- bool isDelim = false;
- String c;
- for (int i = 0; i < data.Length; i++) {
- c = data.Substring(i, 1);
- if (delim.Contains(c)) {
- if (!isDelim) {
- isDelim = true;
- data2 += c;
- }
- continue;
- }
- data2 += c;
- }
- tokens = data2.Split(delimeter.ToCharArray());
- index = 0;
- }
- public int Count() {
- return tokens.Length;
- }
- public bool HasMoreTokens() {
- return (index < (tokens.Length));
- }
- public string NextToken() {
- if (index < tokens.Length) {
- return tokens[index++];
- }
- else {
- return "";
- }
- }
- }
- }
- namespace MyTestApplication1 {
- public class ConvertRadixApp2 {
- public static void PrintUsage() {
- Console.WriteLine("Usage: java ConvertRadixApp");
- Console.WriteLine("Convert radix in a interactive mode, where the maximum radix is 36.");
- }
- public void PrintAbout() {
- Console.WriteLine(" About: Convert radix in a interactive mode.");
- }
- public void PrintMainMenu() {
- Console.WriteLine(" Command: (S)et radix, (A)bout, (Q)uit or E(x)it");
- }
- public void PrintMainPrompt() {
- Console.Write(" Prompt> ");
- }
- public void PrintSubMenu(int srcRadix, int destRadix) {
- Console.WriteLine(" Convert Radix_" + srcRadix + " to Radix_" + destRadix);
- Console.WriteLine(" SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
- }
- public void PrintSubPrompt() {
- Console.Write(" Input Value>> ");
- }
- static string BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- public static string ConvertItoA(long num, int radix) {
- string tmp;
- string ret;
- string arr;
- long q, r;
- bool isNegative = false;
- if (num < 0L) {
- isNegative = true;
- num = -num;
- }
- arr = "";
- q = num;
- r = 0L;
- while (q >= (long) radix) {
- r = q % (long) radix;
- q = q / (long) radix;
- tmp = BASE36.Substring((int)r, 1);
- arr += tmp;
- }
- tmp = BASE36.Substring((int)q, 1);
- arr += tmp;
- if (isNegative) {
- arr += "-";
- }
- ret = "";
- for (int j = 0; j < arr.Length; j++) {
- ret += arr.Substring(arr.Length - j - 1, 1);
- }
- return ret;
- }
- public static long ConvertAtoI(string s, int radix) {
- long ret = 0L;
- bool isNegative = false;
- int len =s.Length;
- char c;
- int i;
- long val = 0L;
- c = s[0];
- if (c == '-') {
- isNegative = true;
- }
- else if (c >= '0' && c <= '9') {
- ret = (long) (c - '0');
- }
- else if (c >= 'A' && c <= 'Z') {
- ret = (long) (c - 'A') + 10L;
- }
- else if (c >= 'a' && c <= 'z') {
- ret = (long) (c - 'a') + 10L;
- }
- if (ret >= (long) radix) {
- Console.WriteLine(" Invalid character!");
- return ret;
- }
- for (i = 1; i < len; i++) {
- c = s[i];
- ret *= radix;
- if (c >= '0' && c <= '9') {
- val = (long) (c - '0');
- }
- else if (c >= 'A' && c <= 'Z') {
- val = (long) (c - 'A') + 10L;
- }
- else if (c >= 'a' && c <= 'z') {
- val = (long) (c - 'a') + 10L;
- }
- if (val >= (long) radix) {
- Console.WriteLine(" Invalid character!");
- return ret;
- }
- ret += val;
- }
- if (isNegative)
- ret = -ret;
- return ret;
- }
- public string ConvertRadix(String s, int srcRdx, int destRdx) {
- long val;
- string ret = "";
- try {
- val = ConvertAtoI(s, srcRdx);
- ret = ConvertItoA(val, destRdx);
- return ret.ToUpper();
- }
- catch (Exception nfx) { ]
- Console.WriteLine(" Error: " + nfx + " cantains some invalid character.");
- ret = "????";
- return ret.ToUpper();
- }
- }
- public void DoConvert(int srcRadix, int destRadix) {
- string cmd;
- string srcStr = "", destStr = "";
- Console.WriteLine();
- PrintSubMenu(srcRadix, destRadix);
- try {
- do {
- PrintSubPrompt();
- while ((cmd = Console.ReadLine()) == null) {
- }
- if ("main()".Equals(cmd)) {
- return;
- }
- else if ("exit()".Equals(cmd) || "quit()".Equals(cmd)) {
- Environment.Exit(0);
- }
- try {
- Convert.ToInt32(cmd, srcRadix);
- srcStr = cmd;
- destStr = ConvertRadix(srcStr, srcRadix, destRadix);
- Console.WriteLine(" ( " + srcStr + " )_" + srcRadix + " ---> ( " + destStr + " )_" + destRadix);
- Console.WriteLine();
- }
- catch (FormatException ex) {
- Console.WriteLine(cmd + ": " + ex);
- }
- } while (true);
- }
- catch (Exception ex) {
- Console.WriteLine("" + ex);
- }
- }
- public void DoStart() {
- char[] seps = { ' ', ',', '\t' };
- string line;
- string cmd;
- int srcRadix = 10, destRadix = 10;
- bool onlyOnce = true;
- try {
- do {
- Console.WriteLine();
- if (onlyOnce) {
- Console.WriteLine(" The supported maximum radix is 36.");
- onlyOnce = false;
- }
- PrintMainMenu();
- PrintMainPrompt();
- while ((cmd = Console.ReadLine()) == null) {
- }
- if ("qQxX".Contains(cmd) && cmd.Length == 1) {
- Environment.Exit(0);
- }
- else if ("aA".Contains(cmd) && cmd.Length == 1) {
- PrintAbout();
- }
- else if ("sS".Contains(cmd) && cmd.Length == 1) {
- Console.Write(" Input the source and target radices (say, 16 2): ");
- line = Console.ReadLine();
- StringTokenizer.Token tok = new StringTokenizer.Token(line, " , \t");
- while (tok.Count() != 2) {
- Console.Write(" Input the source and target radices (say, 16 2): ");
- line = Console.ReadLine();
- tok = new StringTokenizer.Token(line, " , \t");
- }
- try {
- srcRadix = Convert.ToInt32(tok.NextToken());
- destRadix = Convert.ToInt32(tok.NextToken());
- DoConvert(srcRadix, destRadix);
- }
- catch (FormatException ex) {
- Console.WriteLine("" + ex);
- }
- }
- } while (true);
- }
- catch (Exception ex) {
- Console.WriteLine("" + ex);
- }
- }
- // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
- public static void Main(string[] args) {
- if (args.Length > 0 && "-h".Equals(args[0])) {
- PrintUsage();
- Environment.Exit(1);
- }
- ConvertRadixApp2 app = new ConvertRadixApp2();
- app.DoStart();
- }
- }
- }
컴파일> csc ConvertRadixApp.cs
실행> ConvertRadixApp
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 16
Convert Radix_10 to Radix_16
SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
Input Value>> 256
( 256 )_10 ---> ( 100 )_16
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): 16 10
Convert Radix_16 to Radix_10
SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
Input Value>> FFFF
( FFFF )_16 ---> ( 65535 )_10
Input Value>> exit()
'프로그래밍 > C#' 카테고리의 다른 글
7비트 ASCII 코드표 만들기 예제 with C# (0) | 2009.01.19 |
---|---|
진법(radix) 표 만들기 예제 with C# (0) | 2009.01.19 |
황금비율(golden ratio) 구하기 with C# (0) | 2009.01.16 |
현재 시각 알아내기 for C# (0) | 2009.01.16 |
조립제법(Horner의 방법) 예제 for C# (0) | 2009.01.16 |