如何将字符串中的十六进制值转换为数字?

时间:2012-01-06 15:59:09

标签: c#

我有一些代码从串口读取一个字符串,解析一些值(在这种情况下是一个高字节和低字节的表示),然后我交换它们并将它们组合起来,使它们的顺序正确,然后我想将组合值转换为十进制值。

我很难尝试将十六进制表示形式转换为十六进制,然后将结果转换为十进制。

代码在这里:

private void OutputUpdateCallbackclusterTxtBox(string data)
{
string cluster;
string attribute;
string tempvalueHighByte;
string tempvalueLowByte;
string tempvalueHighLowByte; //switched around
int temporarytemp;



if (data.Contains("T00000000:RX len 9, ep 01, clus 0x0201") == true)//find our marker in thestring
{
    if (data.Contains("clus") == true)
    {
        int index = data.IndexOf("clus"); //if we find it find the index in the string it occurs
        cluster = data.Substring(index + 5, 6);  //use this index add 5 and read in 6 characters from the number to get our value
        attribute = data.Substring(index + 5, 1);
        cluster_TXT.Text = cluster; // post the value in the test box
    }
    if (data.Contains("payload") == true)
    {
        int index = data.IndexOf("payload"); //if we find it find the index in the string it occurs
        tempvalueHighByte = data.Substring(index + 20, 2);  //use this index add 20 and read in 2 characters from the number to get our value
        tempvalueLowByte = data.Substring(index + 23, 2);  //use this index add 23 and read in 2 characters from the number to get our value
        tempvalueHighLowByte =  tempvalueLowByte + tempvalueHighByte;


        ConvertToHex(tempvalueHighLowByte);

        temporarytemp= int.Parse(tempvalueHighLowByte);
        temperatureTxt.Text = ((char)temporarytemp).ToString(); // post the value in the text box
    }

2 个答案:

答案 0 :(得分:5)

转换为十六进制并返回C#非常简单,例如

string hex = "FFFFFFFF";

// From hex...
long l = Convert.ToInt64(hex, 16);

// And back to hex...
string hex2 = l.ToString("X");

答案 1 :(得分:3)

试试这个:

int value = Convert.ToInt32("0x0201", 16);