Guest User

HexToByteArray

a guest
May 11th, 2014
181
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     public unsafe static class FastConverter
  2.     {
  3.         static readonly byte[] HiTable =
  4.         {
  5.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  6.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  7.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  8.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  9.             255, 255, 255, 255, 255, 255, 255, 255, 0, 16,
  10.             32, 48, 64, 80, 96, 112, 128, 144, 255, 255,
  11.             255, 255, 255, 255, 255, 160, 176, 192, 208, 224,
  12.             240, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  13.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  14.             255, 255, 255, 255, 255, 255, 255, 160, 176, 192,
  15.             208, 224, 240
  16.         };
  17.  
  18.         static readonly byte[] LoTable =
  19.         {
  20.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  21.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  22.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  23.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  24.             255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
  25.             2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
  26.             255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
  27.             15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  28.             255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  29.             255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
  30.             13, 14, 15
  31.         };
  32.  
  33.         public static byte[] FromHexString(string source)
  34.         {
  35.             // No checks, quality (not null and even chars) of source garanteed
  36.  
  37.             var result = new byte[source.Length >> 1];
  38.  
  39.             fixed (char* sourceRef = source)
  40.             fixed (byte* resultRef = result)
  41.             {
  42.                 fixed (byte* hiRef = HiTable)
  43.                 fixed (byte* lowRef = LoTable)
  44.                 {
  45.                     char* s = &sourceRef[0];
  46.                     byte* r = resultRef;
  47.                     while (*s != 0)
  48.                     {
  49.                         *r = hiRef[*s++];
  50.                         *r++ += lowRef[*s++];
  51.                     }
  52.                     return result;
  53.                 }
  54.             }
  55.         }
  56.     }
RAW Paste Data