471,073 Members | 1,142 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 471,073 developers and data experts.

The opposite of BitConverter.ToString(byte[])

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
0 3771

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

12 posts views Thread by Michi Henning | last post: by
13 posts views Thread by Pohihihi | last post: by
2 posts views Thread by Tedmond | last post: by
1 post views Thread by Water Cooler v2 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.