Commits

Devin Martin committed e011e55

Add conversion extensions

Comments (0)

Files changed (2)

FlipSideOut.Linqpad/Conversion/ConversionExtensions.cs

+namespace FlipSideOut.Linqpad.Conversion
+{
+    using System;
+    using System.IO;
+
+    public static class ConversionExtensions
+    {
+        public static byte[] FromHex(this string hex)
+        {
+            if (hex == null)
+                throw new ArgumentNullException("hex");
+
+            hex = hex.Replace("-", string.Empty);
+
+            if (hex.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
+                hex = hex.Substring(2);
+
+            if (hex.Length % 2 != 0)
+                throw new ArgumentException("hex");
+
+            int NumberChars = (hex.Length / 2);
+
+            byte[] bytes = new byte[NumberChars];
+            StringReader sr = new StringReader(hex);
+            for (int i = 0; i < NumberChars; i++)
+                bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
+            sr.Dispose();
+            return bytes;
+        }
+
+        public static string ToHex(this byte[] ba)
+        {
+            string hex = BitConverter.ToString(ba);
+            return hex.Replace("-", "");
+        }
+
+        public static string ToBinaryString(this byte n)
+        {
+            int pos = 7;
+            int i = 0;
+            char[] output = new char[8];
+            while (i < 8)
+            {
+                if ((n & (1 << i)) != 0)
+                {
+                    output[pos] = '1';
+                }
+                else
+                {
+                    output[pos] = '0';
+                }
+                pos--;
+                i++;
+            }
+            return new string(output);
+        }
+    }
+}

FlipSideOut.Linqpad/FlipSideOut.Linqpad.csproj

     <Reference Include="System.Windows.Forms.DataVisualization" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="Conversion\ConversionExtensions.cs" />
     <Compile Include="Histogram.cs" />
     <Compile Include="RandomEnumerables.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />