在c#中将字符串或字节转换为十六进制十进制

时间:2015-06-18 12:08:18

标签: c# hex byte listener converter

我有一个传感器来获取请求并给我它的值,请求应该是c#中的十六进制格式,如图所示:

enter image description here

我在textbox中输入的请求是这样的:"000100020005030190000212BD"

但正如您所看到的那样,检查了十字checkbox,它将我的请求转换为hex我该怎么做? 这是我发送请求的代码“

 var listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();

using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
{

    // build a request to send to sensor
    var request = new byte[2048];

    stream.Write(request, 0, request.Length);
    // read a response from sensor;
    // note, that respose colud be broken into several parts;
    // you should determine, when reading is complete, according to the protocol for the sensor
    while (true)
    {                    
        // stream.Read calls here
    }
}

数据表:

enter image description here

1 个答案:

答案 0 :(得分:0)

要将字符串转换为十六进制,您可以使用

public string function HexConvert(string InputText)
{
    StringBuilder sb=new StringBuilder();
    char[] lettercollection = InputText.ToCharArray();
    foreach (char letter in lettercollection)
    {
        int integerValue = Convert.ToInt32(letter); //convert to integer
        string hexCode = String.Format("{0:X}", integerValue); //hex generation
        sb.append(hexCode); 
    }
    return sb.ToString(); //your output
}