Convert Byte to Normal Text c #

1

I need to read a byte (Buffer), and convert it to Plain Text, that is, I need to convert to letters and / or numbers from the ASCII table.

I am using this function to convert to ASCII NOTE: when I post:

string result = System.Text.Encoding.UTF8.GetString(buffer);
string result2 = System.Text.Encoding.ASCII.GetString(buffer);
string hexaSemespaco = result2.Replace("#", "");
string test = hexaSemespaco.Substring(1, (hexaSemespaco.Length - 2)); //Tem um símbolo que é ocultado
string convert = ConvertHex(test); //aqui dá o erro, parece que há conflito entre tipos de variaveis, mas não enho ctz'insira o código aqui'

public static string ConvertHex(string hexString)
{
    try
    {
        string ascii = string.Empty;

        for (int i = 0; i < hexString.Length; i += 2)
        {
            string hs = string.Empty;

            hs = hexString.Substring(i, 2);
            uint decval = System.Convert.ToUInt32(hs, 16);
            char character = System.Convert.ToChar(decval);
            ascii += character;

        }

        return ascii;
    }
    catch (Exception ex)
    {
        StreamWriter vWriterr = new StreamWriter(@"c:\POCtest.txt", true);
        vWriterr.WriteLine("ERRO: " + ex.Message);
        vWriterr.Flush();
        vWriterr.Close();
    }
    return "DEU RUIM";
}
    
asked by anonymous 05.09.2018 / 17:20

1 answer

5

For ASCII:

string result = System.Text.Encoding.ASCII.GetString(byteArray);

To Hexadecimal String (Method 1):

string result = BitConverter.ToString(byteArray);

To Hexadecimal String (Method 2):

public static string ConvertHex(byte[] byteArray)
{
  return BitConverter.ToString(ba).Replace("-","");
}

To Hexadecimal String (Method 3):

public static string ConvertHex(byte[] byteArray)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

String Hexa:

string HexStringToString(string hexString) 
{
    if (hexString == null || (hexString.Length & 1) == 1) 
    {
        throw new ArgumentException();
    }
    var sb = new StringBuilder();
    for (var i = 0; i < hexString.Length; i += 2) {
        var hexChar = hexString.Substring(i, 2);
        sb.Append((char)Convert.ToByte(hexChar, 16));
    }
    return sb.ToString();
}

Original answer: StackOverFlow English .

    
05.09.2018 / 17:24