Receiving Data and Converting to String

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 variable tex that I believe has already been transferred to string, is not identical to the literal statement in the case, what treatment should I give the same so that when compared the result is that they are identical?     

asked by anonymous 11.05.2016 / 22:41

1 answer

2

Your text probably has more empty characters at the end (probably ''\u0000'' ), so when you print it looks like the value is only "007F", but actually it has several Trim characters, which means that the strings are different. If you s.Receive these characters from the end, you should get your correct comparison, as the example below shows.

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("
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();
", "") == "007F");

Another alternative is to use only the number of bytes that were received in the %code% call when converting bytes to strings:

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("
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();
", "") == "007F");
    
11.05.2016 / 22:51