Data Reception and String Conversion

Asked

Viewed 43 times

0

byte[] ret = new byte[29];
s.Receive(ret); 

Console.WriteLine("Retorno de Dados" +
    (System.Text.Encoding.ASCII.GetString(ret).Replace("211","")));

string tex = System.Text.Encoding.ASCII.GetString(ret).Replace("211 ", "");
switch (tex)
{
    case "007F": Console.WriteLine("Situação 1"); break;
}
Console.Readkey();

The tex variable that I believe has already transferred to string, is not identical to the literal statement in the case, which treatment should I give the same so that when compared the result is that they are identical?

1 answer

2


Your text probably has more empty characters at the end (probably '\0'), then when you print it looks like the value is only "007F", but actually it has several characters '\u0000', what makes the strings different. If you Trim these characters of the end, you must get your correct comparison, as shown in the example below.

byte[] b = new byte[29];
var bi = 0;
b[bi++] = (byte)'2';
b[bi++] = (byte)'1';
b[bi++] = (byte)'1';

b[bi++] = (byte)'0';
b[bi++] = (byte)'0';
b[bi++] = (byte)'7';
b[bi++] = (byte)'F';

var tex = Encoding.ASCII.GetString(b);
Console.WriteLine("Retorno de Dados: " + tex);
Console.WriteLine("Retorno de Dados: <<" + tex + ">>"); // mostra os outros caracteres

Console.WriteLine(tex.Replace("211", "") == "007F"); // false, o primeiro string tem mais caracteres
Console.WriteLine(tex.Replace("211", "").Replace("\0", "") == "007F");

Another alternative is to use only the number of bytes that were received in the call to s.Receive when to convert bytes to strings:

byte[] ret = new byte[29];
int bytesRecvd = s.Receive(ret); 

Console.WriteLine("Retorno de Dados" +
    (System.Text.Encoding.ASCII.GetString(ret, 0, bytesRecvd).Replace("211","")));

string tex = System.Text.Encoding.ASCII.GetString(ret, 0, bytesRecvd).Replace("211 ", "");
switch (tex)
{
    case "007F": Console.WriteLine("Situação 1"); break;
}
Console.Readkey();
  • Thanks for the help! It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.