forked from mouredev/retos-programacion-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGuillermoqnk.cs
98 lines (71 loc) · 2.45 KB
/
Guillermoqnk.cs
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
using System.Text;
namespace Reto14
{
internal class Guillermoqnk
{
static void Main(string[] args)
{
string input;
Console.WriteLine("Introduce the number to transform: ");
input = Console.ReadLine();
try
{
Console.WriteLine("\nThe number in octal: ");
Console.WriteLine(ConvertToOctal(Convert.ToDecimal(input)));
Console.WriteLine("\nThe number in hexadecimal: ");
Console.WriteLine(ConvertToHexadecimal(Convert.ToDecimal(input)));
}
catch { }
}
public static int ConvertToOctal(decimal input)
{
int numberToTry = (int)input;
List<int> results = new List<int>();
while(numberToTry >= 8)
{
int rest = numberToTry % 8;
results.Add(rest);
numberToTry = numberToTry / 8;
}
results.Add(numberToTry);
StringBuilder output = new StringBuilder();
results.Reverse();
foreach(int result in results)
{
output.Append(result);
}
return Convert.ToInt32(output.ToString());
}
public static string ConvertToHexadecimal(decimal input)
{
Dictionary <int, string> hexaValues= new Dictionary<int, string>()
{
{0, "0"}, {1,"1"}, {2,"2"}, {3,"3"}, {4,"4"}, {5,"5"}, {6,"6"}, {7, "7"}, {8, "8"}, {9,"9"}, {10, "A"}, {11, "B"}, {12, "C"},{13, "D"},{14, "E"}, {15, "F"}
};
int numberToTry = (int)input;
List<string> results = new List<string>();
while (numberToTry >= 16)
{
int rest = numberToTry % 16;
string hexa = String.Empty;
if(hexaValues.TryGetValue(rest, out hexa))
{
results.Add(hexa);
}
numberToTry = numberToTry / 16;
}
string hexal;
if (hexaValues.TryGetValue((int)numberToTry, out hexal))
{
results.Add(hexal);
}
StringBuilder output = new StringBuilder();
results.Reverse();
foreach (string result in results)
{
output.Append(result);
}
return output.ToString();
}
}
}