Question

I have a string in c# which contains the following..

SMDR#0D#0APCCSMDR#0D#0A

Now as per my requirement i need to parse this into byte[] with the same formate..I have to show the byte[] as

SMDR#0D#0APCCSMDR#0D#0A

This i am needed because the my function takes arguments in this formate of byte[] and the value that i need to pass is this only..

SMDR#0D#0APCCSMDR#0D#0A

How to achieve this.Do i need to change in the string formate or byte[]..

Was it helpful?

Solution 2

I'm really confused with your question, but if you need your string represented as byte[] you can use LINQ:

var output = input.Select(x => (byte)x).ToArray();

OTHER TIPS

You can do it using following code, I hope this will answer your question.

FROM http://www.dotnetperls.com/convert-string-byte-array

using System;
using System.Text;

class Program
{
    static void Main()
    {
  // Input string.
  const string input = "Dot Net Perls";

  // Invoke GetBytes method.
  // ... You can store this array as a field!
  byte[] array = Encoding.ASCII.GetBytes(input);

  // Loop through contents of the array.
  foreach (byte element in array)
  {
      Console.WriteLine("{0} = {1}", element, (char)element);
  }
    }
}

Well, here is hopefully a more explanatory answer...

Getting the bytes doesn't technically depend on the encoding, since it is just memory. However, interpreting the sequence of bytes does. What encoding does the function you are calling expect?

If it is expecting raw ascii bytes:

Encoding.ASCII.GetBytes("hello, 你是天才"); // 11 bytes. chinese truncated

If it is expecting the UTF-8 data (1 byte ascii, 2-4 bytes for others):

Encoding.UTF8.GetBytes("hello, 你是天才"); // 19 bytes, as utf8 

If it wants a double width characters (2 bytes each, UCS-2):

Encoding.Unicode.GetBytes("hello, 你是天才") // 22 bytes

And so on and on. Check out the System.Text.Encoding class for more details and options.

just try this code

string str="SMDR#0D#0APCCSMDR#0D#0A";
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
 foreach (var item in bytes)
        {
            Response.Write((char)item);
        }

for more clarify read from http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top