Binary to hexadecimal converter - CSharp System

CSharp examples for System:Math Number

Description

Binary to hexadecimal converter

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/*from   w ww  .  j a v  a 2 s .  com*/

public class Main{
        /// <summary>
        /// Binary to hexadecimal converter
        /// </summary>
        public static string BinToHex(string value)
        {
            // Adding leading zeros
            if (value.Length % 4 != 0)
            {
                int repetitions = 4 - (value.Length % 4);
                string add = new string('0', repetitions);
                value = add + value;
            }

            List<string> bytes = new List<string>();

            for (int start = 0, end = 4; start < value.Length; start += 4)
            {
                bytes.Add(value.Substring(start, end));
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < bytes.Count; i++)
            {
                switch (bytes[i])
                {
                    case "0000": sb.Append("0"); break;
                    case "0001": sb.Append("1"); break;
                    case "0010": sb.Append("2"); break;
                    case "0011": sb.Append("3"); break;
                    case "0100": sb.Append("4"); break;
                    case "0101": sb.Append("5"); break;
                    case "0110": sb.Append("6"); break;
                    case "0111": sb.Append("7"); break;
                    case "1000": sb.Append("8"); break;
                    case "1001": sb.Append("9"); break;
                    case "1010": sb.Append("A"); break;
                    case "1011": sb.Append("B"); break;
                    case "1100": sb.Append("C"); break;
                    case "1101": sb.Append("D"); break;
                    case "1110": sb.Append("E"); break;
                    case "1111": sb.Append("F"); break;
                }
            }

            return sb.ToString();
        }
}

Related Tutorials