473,609 Members | 1,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The opposite of BitConverter.To String(byte[])

1 New Member
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 4103

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

Similar topics

4
16227
by: Greg Ennis | last post by:
If I run the following code: Byte bytes = System.Text.Encoding.ASCII.GetBytes("test"); return BitConverter.ToString(bytes); I get the string "74-65-73-74" back. My question is, what is the easiest way to convert the string back to "test"? Can it be done without breaking the string and using a loop, etc.? I have tried many methods, but can't find a way without using a loop. It
12
7307
by: Michi Henning | last post by:
Looking at the language spec, I can't find a statement about the byte order for value types, such as int, float, etc. Are they guaranteed to be little-endian or big- endian? I know that, on a little-endian machine, the byte order is little-endian. But what if I run C# on a big- endian machine, say, using Mono? Does the C# language (or IL) make any guarantees as to the byte order?
4
4293
by: CSharpener | last post by:
This should be *so* easy! How do I convert a Byte or int to a binary string representation in C# In JavaScript, it goes like this for an int: javascript:(123).toString(2 or javascript:(0xFE).toString(2 No problem. So, how do I do the same in C#? What simple thing am I missing
4
4702
by: Ping | last post by:
Hi, All, We can use BitConverter.ToString(byte) to a string, but how to get the byte from a string like "AD-A6-0D-1F"?
13
2989
by: Pohihihi | last post by:
I am getting Guid using new Guid() when I say new Guid().ToString() I get 10856f25-2759-0358-159c-ff7e0759c800 but when I say
2
2884
by: Tedmond | last post by:
Can anyone tell me how to convert a byte to bit pattern? e.g. Byte b = 1; after conversion = 00000001 Tedmond
1
2156
by: Water Cooler v2 | last post by:
What's the way to convert a byte to a hexadecimal?
2
3721
by: gizmo | last post by:
Hi, Here's a little hack I put together to try to get to the bottom of a problem I'm having with trying to base64 encode a hash value. The hash value contains character codes 135 and 130 amongst others. This snippet will set up a string of chars 190, 135, 130, 73, 242, 243, 10. It puts them into a bytearray. string encodedData;
0
7164
by: BobbyS | last post by:
I've a xml file.I'm taking its data passing it to a method in string form and converting that string "xmlData" to a array of bytes by Convert.FromBase64String(xmlData) but I'm getting a exception "Invalid character in Base-64 string." My code is like this. XmlTextReader xmlReader = new XmlTextReader(XML_LAYOUT_FILE_PATH); XmlDocument doc = new XmlDocument(); doc.Load(xmlReader); StringWriter writer...
0
8139
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8091
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8579
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8555
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8408
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6064
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5524
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4032
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2540
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.