Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class binToHexDirectly
- {
- static string ToHex(string digitStr)
- {
- string output = "";
- switch (digitStr)
- {
- case "0000":
- output = "0";
- break;
- case "0001":
- output = "1";
- break;
- case "0010":
- output = "2";
- break;
- case "0011":
- output = "3";
- break;
- case "0100":
- output = "4";
- break;
- case "0101":
- output = "5";
- break;
- case "0110":
- output = "6";
- break;
- case "0111":
- output = "7";
- break;
- case "1000":
- output = "8";
- break;
- case "1001":
- output = "9";
- break;
- case "1010":
- output = "10";
- break;
- case "1011":
- output = "11";
- break;
- case "1100":
- output = "12";
- break;
- case "1101":
- output = "13";
- break;
- case "1110":
- output = "14";
- break;
- case "1111":
- output = "15";
- break;
- }
- return output;
- }
- static void Main()
- {
- Console.WriteLine("enter a Binary number to see its Hexadecimal representation:");
- string number = Console.ReadLine();
- char[] tmpChar = number.ToCharArray();// Converting to char array so that every digit is sepparated from the others.
- string[] tmpStr = new string[tmpChar.Length];//Converting to string for ease of control over every digit alone.
- string tmp = "";
- string[] output = new string[tmpStr.Length];
- string result = "";
- int j = 0;
- int m = 0;
- for (int i = 0; i < tmpChar.Length; i++)
- {
- if(j == 4)
- {
- char[] rev1 = tmp.ToCharArray();
- tmp = "";
- Array.Reverse(rev1);
- for (int k = 0; k < rev1.Length; k++)
- {
- tmp += rev1[k];
- }
- tmpStr[m] = tmp;
- m++;
- j = 0;
- tmp = "";
- }
- tmp += tmpChar[tmpChar.Length - i - 1].ToString();
- j++;
- if (i == tmpChar.Length - 1 && j < 4)
- {
- if (j == 1)
- {
- tmp += "000";
- }
- else if (j == 2)
- {
- tmp += "00";
- }
- else if (j == 3)
- {
- tmp += "0";
- }
- char[] rev = tmp.ToCharArray();
- tmp = "";
- Array.Reverse(rev);
- for (int s = 0; s < rev.Length; s++)
- {
- tmp += rev[s];
- }
- tmpStr[m] = tmp;
- tmp = "";
- }
- }
- for (int i = 0; i < tmpStr.Length; i++)
- {
- output[i] = ToHex(tmpStr[tmpStr.Length - i - 1]);
- //Solving problem with Letters!
- switch (output[i])
- {
- case "10":
- output[i] = "A";
- break;
- case "11":
- output[i] = "B";
- break;
- case "12":
- output[i] = "C";
- break;
- case "13":
- output[i] = "D";
- break;
- case "14":
- output[i] = "E";
- break;
- case "15":
- output[i] = "F";
- break;
- default:
- break;
- }
- }
- for (int i = 0; i < output.Length; i++)
- {
- result += output[i];
- }
- Console.WriteLine("\nTo Hexadecimal: {0}", result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement