none
How to convert the string to byte in c# ?

    Question

  • hello C# gurus,

    i am trying to convert string to byte using this code, but it gives error pls help me..

     

    public static byte[] StringToByte(string InString) {

    string[] ByteStrings;

    ByteStrings = InString.Split(" ".ToCharArray());

    byte[] ByteOut;

    ByteOut = new byte[ByteStrings.Length-1];

    for (int i = 0;i==ByteStrings.Length-1;i++) {

    ByteOutIdea = Convert.ToByte(("0x" + ByteStringsIdea));

    }

    return ByteOut;

    }

    Friday, January 27, 2006 2:04 PM

All replies

  • The easiest way to convert a string into a byte array is to use the GetBytes() method of an instantiated text encoding class, consider this example:

        System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
        Byte[] bytes = Encoding.GetBytes(yourString);


    • Proposed as answer by Wanaco Tuesday, June 08, 2010 10:39 PM
    • Edited by OmegaManMVP, Moderator Wednesday, August 01, 2012 4:47 PM Changed encoding (#Fail) to Encoding
    Friday, January 27, 2006 2:20 PM
    Moderator
  • public static byte[] ToByteArray(string StringToConvert)

    {

    char[] CharArray = StringToConvert.ToCharArray();

    byte[] ByteArray = new byte[CharArray.Length];

    for (int i = 0; i < CharArray.Length; i++)

    {

    ByteArrayIdea = Convert.ToByte(CharArrayIdea);

    }

    return ByteArray;

    }

     

    Give that a go...

    Friday, January 27, 2006 2:29 PM
  • Hi Ghanshyam

    Could you give us an example of what your input string looks like?  In the meantime here are couple areas you may want to check...

    When you create ByteOut I notice that you are creating to the Length - 1 of the initial ByteStrings.  If I'm understanding your code correctly it looks as if you want to take each character from the InString and convert that to a byte.  In that's the case then this will be a 1-to-1 conversion so you'll need to intialize ByteStrings to be the length of InString.  Consider what would happen if you had an InString of 1.  ByteString would be intialized to 0 (Length - 1) meaning that when you tried to assign a value to ByteString at the end of the for loop you would recieve an IndexOutOfRangeException.

    Next, Convert.ToByte(...) returns a single byte but your code is currently attempting to assign that to an array as follows:

    ByteOut = Convert.ToByte(("0x" + ByteStrings)); // where ByteOut is an array.

    You will need to actually assign the resultse of Convert.ToByte(...) to an individual element of the array as follows:

    ByteOutIdea = Convert.ToByte(("0x" + ByteStrings)); // where 'i' is the iterator of the for loop.

     

    I suspect that you will also need to massage the string further to get it in a for suitable for a byte as well, but we can cross that bridge later (I want to make sure i understand your intentions correctly before i make any suggestions).

    Hope this helps!

    Jeremy

     

     

     

     

     

     

    Friday, January 27, 2006 2:33 PM
  • Hello,

    I am trying to do something along the same lines, and I am looking for some guidance (and maybe I can be of some help).

    Basically, I need to read decimal representations of byte characters in, and save them in a byte array.  Each line in the file I'm reading will be an array of bytes once I'm done.  Here's an example of one line of data:

    Code Block

    string temp = "255 255 255 0 243 8 50";


    As you can see, there are 7 bytes represented in this line, when i am finished, I want a byte[] with the 7 bytes in it.

    Here's what I'm thinking codewise:
    Code Block

    string[] byteStrings = temp.Split(" ");

    byte[] byteOut = new byte[byteStrings.Length];

    for(int i = 0; i < byteStrings.Length; i++)

    {

        byteOut[i] = Convert.ToByte(byteStrings[i]);

    }


    Does this look like it will work?  I am going to test it now and I will post a reply if it works or not.

    Thanks much.
    Wednesday, January 02, 2008 10:19 PM
  • Folks, be carefull when using ASCIIEncoding for such conversion from byte array. As you may know, byte array can contain values that goes beyond 128. What we usually forget is that ASCIIEncoding works with 7 bits only. When converting, the values will get mixed up.

    See the sample below:

    byte[] byteArray = {192, 65, 66, 67}; 
    string str1 = System.Text.Encoding.ASCII.GetString(byteArray); 
    string str2 = System.Text.Encoding.Unicode.GetString(byteArray); 
    string str3 = System.Text.Encoding.UTF8.GetString(byteArray); 
    string str4 = System.Text.Encoding.Default.GetString(byteArray); 
     
    byte[] res1 = System.Text.Encoding.ASCII.GetBytes(str1);//returns {63, 65, 66, 67} 
    byte[] res2 = System.Text.Encoding.Unicode.GetBytes(str2);//returns  {192, 65, 66, 67} 
    byte[] res3 = System.Text.Encoding.UTF8.GetBytes(str3);//returns {239, 191, 189, 65, 66, 67} 
    byte[] res4 = System.Text.Encoding.Default.GetBytes(str4);//returns {192, 65, 66, 67}; 
     


    So I would consider using unicode for this kind of conversion.


    Regards,
    • Proposed as answer by kennyshu Tuesday, December 16, 2008 4:17 PM
    Thursday, October 30, 2008 3:44 PM
  • simply you can use only two lines of code for getting byte array from string :  

        public static byte[] StrToByteArray(string str)
        {
                System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
                return encoding.GetBytes(str);
        }

    for full description about how to convert string to byte array try this

    http://www.authorcode.com/how-to-convert-a-string-into-byte-using-c-and-vb-net/


    Hirendra
    Wednesday, September 28, 2011 10:57 AM
  • What kind or exception you are having, if the value of the byte exist more than 255 or less than Zero you will get exception. it will be good if you specify the what kind of error you are getting for the given input.
    • Proposed as answer by Sebbo176 Wednesday, August 01, 2012 9:13 AM
    Wednesday, September 28, 2011 11:36 AM
  • You typically use the String.Split(' ') method when you have a string which represents bytes separated by spaces such as "33 47 82".  Before you can properly convert this string of byte values to an array of bytes, you must decide whether your string represents decimal values, hex values, or another numeric base.  The important thing to remember here is that your byte array will be limited to 8 bits per entry.  This means, if your array contains decimal values, they will be limited to the range 0 to 255.  If your array represents hex values, they will be limited to the range from 00 to FF.  Now for code that has been tested to work:

    Decimal byte string:

       String strInString = "255 44 18";

       String[] strInputSplit = strInString.Split(' ');

       byte[] byteOut = new byte[strInputSplit.Length];

       for (int i = 0; i < strInputSplit.Length; i++)

       {
          byteOut[i] = Convert.ToByte(strInputSplit[i]);
       }

    The output is the same as byte[] byteOut = {255, 44, 18};

    Hex byte string:

       String strInString = "FF 0E 12";
       string[] strInputSplit = strInString.Split(' ');
       byte[] byteOut = new byte[strInputSplit.Length];
       for (int i = 0; i < strInputSplit.Length; i++)
       {
          byteOut[i] = Convert.ToByte(strInputSplit[i], 16);
       }

    This gives an output equivalent to byte[] byteOut = {0xFF, 0x0E, 0x12};

    If you view these values in the watch window you will need to toggle "Hexadecimal Display" to see the values in decimal or hex.

    The code...

             String strInString = "255 14 18";
             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
             Byte[] bytes = encoding.GetBytes(strInString);

    takes each individual character in the string and converts it into its ASCII equivalent.  In this case, you better make sure your string contains ASCII printable characters, or you will not get the proper values (they will be truncated to 7 bits).  If you truly want to convert a string to 8 bit bytes use:        

       String strInString = "255 14 18";
       Byte[] bytes = Encoding.GetEncoding(28591).GetBytes(strInString);

    If you think it doesn't make a difference try:

       String strInString = "255 14 18" + '\u0087';
       Byte[] bytes = Encoding.GetEncoding(28591).GetBytes(strInString);

    In the second example I appended a character in the extended ASCII range.  This will fail in the code presented by Brendan Grant (14,350 points).

    Monday, June 04, 2012 10:24 PM
  • I'm wondering why OmegaMan (MVP, Moderator) changed the code after 6 and a half years. Especially since he changed "encoding" (a local variable of type "System.Text.ASCIIEncoding") to "Encoding" (a class), which breaks the code, since "Encoding.GetBytes(string)" won't work, and "encoding.GetBytes(string)" does work.
    • Proposed as answer by Bertasoft Monday, June 10, 2013 5:04 PM
    Friday, February 15, 2013 7:04 PM
  • you can use System.Text.Encoding.Unicode.GetBytes() to retrieve the set of bytes that Microsoft.Net would using to represent the characters.

    Using UTF8 conversion

    byte[] bArray = Encoding.UTF8.GetBytes (inputString);

    Using ASCII conversion

    byte[] bArray = Encoding.ASCII.GetBytes (inputString);

    C# Example...C# String to bytearray

    Tuesday, May 27, 2014 5:44 AM
  • Modified version

    public static byte[] StringToByte(string InString) {
    	string[] ByteStrings;
    
    	ByteStrings = InString.Split(" ".ToCharArray());
    
    	byte[] ByteOut;
    
    	ByteOut = new byte[ByteStrings.Length];
    
    	for (int i = 0; i <= (ByteStrings.Length - 1); i++) {
    		ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
    	}
    	return ByteOut;
    }

    Simplified

    public static byte[] StringToByte(string InString) {
    	string[] ByteStrings =	 InString.Split(" ".ToCharArray());
    	byte[] ByteOut =  new byte[ByteStrings.Length];
    
    	for (int i = 0; i <= (ByteStrings.Length - 1); i++) 
    		ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
    
    	return ByteOut;
    }

    Optimized with LINQ

    public static byte[] StringToByte(string InString) {
    	return (from b in InString.Split(' ')
    			select Byte.Parse(b, System.Globalization.NumberStyles.HexNumber)).ToArray();
    }


    Muthukrishnan Ramasamy
    net4.rmkrishnan.net
    Use only what you need, Reduce global warming

    • Proposed as answer by SundaramR Wednesday, May 28, 2014 7:03 AM
    Tuesday, May 27, 2014 10:48 AM