Converting byte array to string.

  • Thread starter Thread starter Prabhu
  • Start date Start date
P

Prabhu

Hi,

We are having problem in converting a byte array to string, The byte array
has char(174), char(175), char(240), char(242) and char(247) as delimiters
for the message.

when we use "System.Text.Encoding.ASCII.GetString(bytearray)" of .Net
library, we found that the char (delimiters) specified above are replaced
with different char.

Can any one help me in this ?

My sample program is,

using System;

using System.Text;

using System.Net.Sockets;

namespace StrideAPIParse

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

public static char PACKET_BEGIN_DELIMIT = (char)175;

public static char HEADER_DELIMIT = (char)240;

public static char RECORD_FIELD_DELIMIT = (char)242;

public static char RECORD_DELIMIT = (char)247;

public static char PACKET_END_DELIMIT = (char)174;

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

//

// TODO: Add code to start application here

//


TcpClient tcpClient = new TcpClient();

tcpClient.Connect("172.16.10.164", 5403);

NetworkStream networkStream = tcpClient.GetStream();

byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

int readleagth = networkStream.Read(bytes, 0, (int)
tcpClient.ReceiveBufferSize);

bytes[readleagth] = 0;

String stridemsg = Encoding.ASCII.GetString(bytes);

string [] msg = stridemsg.Split(HEADER_DELIMIT);

foreach(string m in msg)

{

Console.WriteLine(m);

}

tcpClient.Close();

Console.ReadLine();

}

}

}
 
Prabhu,

The reason for this is that 174, 175, 240, and 242 are not valid ascii
codes. They are valid in the set of extended ascii codes, but I don't
believe that there is an encoding that .NET provides which will handle this.
You will have to implement your own, or find an existing one.

Another possibility would be to pad every byte with an empty byte, and
then using the UnicodeEncoding class to decode your bytes into a string.
This should produce valid values that you can work with.

Hope this helps.
 
I believe the Encoding.ASCII uses a 7-bit set. Not sure which one you
should use.
 
Prabhu said:
We are having problem in converting a byte array to string, The byte array
has char(174), char(175), char(240), char(242) and char(247) as delimiters
for the message.

when we use "System.Text.Encoding.ASCII.GetString(bytearray)" of .Net
library, we found that the char (delimiters) specified above are replaced
with different char.

Can any one help me in this ?

Have a look at http://www.pobox.com/~skeet/csharp/unicode.html

I suspect Encoding.Default is what you're after, but it looks like
you're not really after those *characters*, you're after those *bytes*
as delimiters. In that case, you should process the delimiters first,
and then decode each chunk of bytes between delimiters.
 
Back
Top