C# 如何将字符串中的十六进制值转换为数字?
我有一些代码从串口读取字符串,解析一些值(在本例中是高字节和低字节的表示),然后交换它们并将它们按正确的顺序组合,然后我想将组合值转换为十进制值 我很难将十六进制表示形式转换为字符串,然后将结果转换为十进制 代码如下:C# 如何将字符串中的十六进制值转换为数字?,c#,C#,我有一些代码从串口读取字符串,解析一些值(在本例中是高字节和低字节的表示),然后交换它们并将它们按正确的顺序组合,然后我想将组合值转换为十进制值 我很难将十六进制表示形式转换为字符串,然后将结果转换为十进制 代码如下: private void OutputUpdateCallbackclusterTxtBox(string data) { string cluster; string attribute; string tempvalueHighByte; string tempvalueLo
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
}
在C#中转换为十六进制并返回同样简单,例如
string hex = "FFFFFFFF";
// From hex...
long l = Convert.ToInt64(hex, 16);
// And back to hex...
string hex2 = l.ToString("X");
试试这个:
int value = Convert.ToInt32("0x0201", 16);
你为什么不直接转换成十进制呢?为什么是“to string”中间步骤?这是我的错误逻辑,一次只执行一个步骤,当然不需要转换为hex。谢谢Steve,我尝试了上面的方法,但编译器抱怨“无法将“int”类型隐式转换为“string”嗨,乔治,我尝试了你的解决方案,效果很好,只需将lont转换为string,这样我就可以显示在文本框中,谢谢Nick