How to convert the string to byte in c# ?


  • 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;


    viernes, 27 de enero de 2006 14:04

Todas las respuestas

  • 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);

    • Propuesto como respuesta Wanaco martes, 08 de junio de 2010 22:39
    • Editado OmegaManMVP, Moderator miércoles, 01 de agosto de 2012 16:47 Changed encoding (#Fail) to Encoding
    viernes, 27 de enero de 2006 14:20
  • 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...

    viernes, 27 de enero de 2006 14:29
  • 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!








    viernes, 27 de enero de 2006 14:33
  • 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.
    miércoles, 02 de enero de 2008 22:19
  • 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.

    • Propuesto como respuesta kennyshu martes, 16 de diciembre de 2008 16:17
    jueves, 30 de octubre de 2008 15:44
  • 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

    miércoles, 28 de septiembre de 2011 10:57
  • 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.
    • Propuesto como respuesta Sebbo176 miércoles, 01 de agosto de 2012 9:13
    miércoles, 28 de septiembre de 2011 11:36
  • 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).

    lunes, 04 de junio de 2012 22:24
  • 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.
    • Propuesto como respuesta Bertasoft lunes, 10 de junio de 2013 17:04
    viernes, 15 de febrero de 2013 19:04