String to Hex and Hex to String via LINQ

By Peter Bromberg

Here are a couple of cool "LINQ-ified" ways to convert a string to a hexadecimal string, and convert the hexadecimal string back to the original string. The sample assumes you want to encode some querystring items.

string s = "?test=1&x=username&pagecount=10";
           //string to HEX
            string hex = BitConverter.ToString(System.Text.Encoding.UTF8.GetBytes(s)).Replace("-", string.Empty);
            // HEX to string
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(hex);      
             string s2= System.Text.Encoding.UTF8.GetString( Enumerable.Range(0, hex.Length).Where(x => 0 == x % 2).Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).ToArray())  ;

String to Hex and Hex to String via LINQ  (879 Views)