HEX String Conversions With LINQ

By Peter Bromberg

Often you may want to convert a string to it's Hexadecimal string equivalent, or convert a HEX string back to the original text. This is useful in situations where, for example, you would like to obfuscate the query string on a URL.

Here is a sample Console app with two methods:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HexConverter
    class Program
         static void Main(string[] args)
             string test = "Holy Cow, Batman! We're surrounded by Indians!";
            string result = ToHex(test);
             // Output: 486F6C7920436F772C204261746D616E2120576527726520737572726F756E64656420627920496E
             string original = FromHex(result);
           Console.WriteLine(original );
             // Output: Holy Cow, Batman! We're surrounded by Indians!

     public static string ToHex( string stuff)
           return BitConverter.ToString(System.Text.Encoding.UTF8.GetBytes(stuff)).Replace("-", String.Empty);

         public static string FromHex(string hex)
             return 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());



HEX String Conversions With LINQ  (1932 Views)