通过套接字接收原始HEX并转换为字符串

时间:2017-03-01 08:16:02

标签: c# sockets character-encoding hex data-conversion

我有以下问题,我尝试从TCP / IP套接字接收原始HEX值并将其写在txt文件中,只有我在将此原始HEX数据转换为UTF-8字符串时遇到一些问题。我使用以下方法:

TcpClient client = new TcpClient("192.168.200.91", 2101);
NetworkStream netStream = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
netStream.Read(bytes, 0, (int)client.ReceiveBufferSize);

string returndata = Encoding.UTF8.GetString(bytes);

using (var writer = new StreamWriter(@"C:\Users\ -\Documents\test.txt", false, Encoding.UTF8))
{
    writer.WriteLine(returndata);
}

返回:*þý% ˆ ꇅ ÿ Œ7ºe B %û

如何成功读取原始HEX数据并将其转换为可读字符串?

1 个答案:

答案 0 :(得分:1)

使用BitConverter:

TcpClient client = new TcpClient("192.168.200.91", 2101);
NetworkStream netStream = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
int bytesRead = netStream.Read(bytes, 0, (int)client.ReceiveBufferSize);

string returndata = BitConverter.ToString(bytes, 0, bytesRead).Replace("-", "")

using (var writer = new StreamWriter(@"C:\Users\ -\Documents\test.txt", false, Encoding.UTF8))
{
    writer.WriteLine(returndata);
}