1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
int FromHex(string s) {
int res = 0;
foreach (char ch in s) {
if ('0' <= ch && ch <= '9') res = 16 * res + (ch - '0');
else if ('a' <= ch && ch <= 'f') res = 16 * res + (ch - 'a' + 10);
else if ('A' <= ch && ch <= 'A') res = 16 * res + (ch - 'A' + 10);
else throw new FormatException();
}
return res;
}
//----- convert decimal string to int
int FromDec(string s) {
int res = 0;
foreach (char ch in s) {
if ('0' <= ch && ch <= '9') res = 10 * res + (ch - '0');
else throw new FormatException();
}
return res;
}
//----- convert octal string to int
int FromOct(string s) {
int res = 0;
foreach (char ch in s) {
if ('0' <= ch && ch <= '7') res = 8 * res + (ch - '0');
else throw new FormatException();
}
return res;
}
//----- convert binary string to int
int FromBin(string s) {
int res = 0;
foreach (char ch in s) {
if (ch == '0') res = 2 * res;
else if (ch == '1') res = 2 * res + 1;
else throw new FormatException();
}
return res;
}
//----- parse and return the value of the TextBox val
int Value() {
string s = val.Text;
if (s.Length == 0) throw new FormatException();
else if (s.Length > 2 && s[0] == '0') {
if (s[1] == 'x') return FromHex(s.Substring(2));
else if (s[1] == 'o') return FromOct(s.Substring(2));
else if (s[1] == 'b') return FromBin(s.Substring(2));
}
return FromDec(s);
}
//----- convert n to numeric string of base b
string ToNumeric(int n, int b) {
StringBuilder buf = new StringBuilder();
do {
buf.Append((char)(n % b + '0'));
n = n / b;
} while (n != 0);
StringBuilder s = new StringBuilder();
for (int i = buf.Length - 1; i >= 0; i--) s.Append(buf[i]);
return s.ToString();
}
//-------------- event handlers ---------------------
//---- Convert TextBox val to hexadecimal format
public void ToHex(object sender, EventArgs e) {
try {
val.Text = "0x" + Value().ToString("x8");
error.Text = "";
} catch (FormatException) {
error.Text = errMsg;
}
}
//---- Convert TextBox val to decimal format
public void ToDec(object sender, EventArgs e) {
try {
val.Text = Value().ToString();
error.Text = "";
} catch (FormatException) {
error.Text = errMsg;
}
}
//---- Convert TextBox val to octal format
public void ToOct(object sender, EventArgs e) {
try {
val.Text = "0o" + ToNumeric(Value(), 8);
error.Text = "";
} catch (FormatException) {
error.Text = errMsg;
}
}
//---- Convert TextBox val to binary format
public void ToBin(object sender, EventArgs e) {
try {
val.Text = "0b" + ToNumeric(Value(), 2);
error.Text = "";
} catch (FormatException) {
error.Text = errMsg;
}
}
}
}
|