using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string BinaryStr = "1000101001110"; int Index = 0; int Decimal = 0; foreach (char Char in BinaryStr.Reverse()) { if (Index != 0) { Decimal += Index * 2 * Convert.ToInt32(Char.ToString()); Index = Index * 2; } else { Decimal += Convert.ToInt32(Char.ToString()); Index++; } } Console.WriteLine("hexadecimal no for : " + BinaryStr + " => " + Decimal.ToString()); string Hexa1 = toHex(Convert.ToInt64(Decimal)); Console.WriteLine("hexadecimal no for : " + BinaryStr + " => " + Hexa1 ); } public static string toHex(Int64 d) { var r = d % 16; string result; if (d - r == 0) result = toChar(Convert.ToInt32(r)); else result = toHex((d - r) / 16) + toChar(Convert.ToInt32(r)); return result; } public static string toChar(int n) { const string alpha = "0123456789ABCDEF"; return alpha.Substring(n, 1); } }
ushort result = Convert.ToUInt16(str, 2);
result.ToString("X4");
public static string BinaryStringToHexString(string binary) { StringBuilder result = new StringBuilder(binary.Length / 8 + 1); // TODO: check all 1's or 0's... Will throw otherwise int mod4Len = binary.Length % 8; if (mod4Len != 0) { // pad to length multiple of 8 binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0'); } for (int i = 0; i < binary.Length; i += 8) { string eightBits = binary.Substring(i, 8); result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2)); } return result.ToString(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)