By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,685 Members | 1,243 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

The opposite of BitConverter.ToString(byte[])

P: 1
Hello,

For saving 1 hour of your precious time use this function for parsing a text to a byte array:

Expand|Select|Wrap|Line Numbers
  1.    /// <summary>
  2.         /// Converts the string representation of an array of numbers in a specified base to an
  3.         /// equivalent 8-bit unsigned integer array (byte[]).
  4.         /// </summary>
  5.         /// <param name="text">A System.String containing an array of numbers separated by '\r' or '\n' or '\t' or ' ' (space) or ',' (comma) or '-'.</param>
  6.         /// <param name="numericBase">The base of the numbers in text, which must be 2, 8, 10, or 16.</param>
  7.         /// <returns>A 8-bit unsigned integer array (byte[]) -or- null if text is null.</returns>
  8.         private byte[] ToBytes(string text, int numericBase)
  9.         {
  10.             if (text == null)
  11.             {
  12.                 return null;
  13.             }
  14.             else
  15.             {
  16.                 var tokens = text.Split(new char[] { '\r', '\n', '\t', ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries);
  17.                 var list = new List<byte>();
  18.  
  19.                 for (var index = 0; index < tokens.Length; index++ )
  20.                 {
  21.                     var token = tokens[index];
  22.                     try
  23.                     {
  24.                         list.Add(Convert.ToByte(token, numericBase));
  25.                     }
  26.                     catch (Exception ex)
  27.                     {
  28.                         //index is 0 based -but- position is 1 based
  29.                         var position = index + 1;
  30.                         throw new Exception(ex.Message + " Token: '" + token + "' at position " + position + ".");
  31.                     }
  32.                 }
  33.                 return list.ToArray();
  34.             }
  35.         }
  36.  
Regards
Jan 5 '10 #1
Share this Article
Share on Google+