2012-01-06 53 views
0

我有一些代码从串口读取一个字符串,解析一些值(在这种情况下,表示高字节和低字节),然后交换它们并合并它们,以便它们按正确的顺序,然后我想将合并后的值转换为十进制值。如何将字符串中的十六进制值转换为数字?

我很难试图将十六进制表示形式转换为十六进制的字符串,然后将结果转换为十进制。

的代码是在这里:

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 
    } 
+0

你为什么不直接转换成十进制?为什么要“串”中介步骤? – Adrian 2012-01-06 16:02:05

+0

它是我的错误逻辑,只需一次一步,肯定不需要转换为十六进制 – 2012-01-06 16:51:32

回答

5

转换为十六进制和背部在C#一样简单,例如

string hex = "FFFFFFFF"; 

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

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

嗨乔治,我试过你的解决方案,它工作正常,只需要将lont转换为字符串,这样我就可以显示在文本中盒,谢谢尼克 – 2012-01-06 16:50:22

3

试试这个:

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

谢谢史蒂夫,我试过以上,但编译器抱怨“不能隐式转换类型'int'字符串' – 2012-01-06 16:45:20

+0

@ user1134631:抱歉的错误。我更新了代码 – 2012-01-07 12:16:06

相关问题