如何将字符串中的十六进制值转换为数字
本文关键字:转换 数字 十六进制 字符串 | 更新日期: 2023-09-27 18:19:34
我有一些代码,它从串行端口读取字符串,解析一些值(在本例中是高字节和低字节的表示),然后交换它们并组合它们,使它们按正确的顺序排列,然后我想将组合的值转换为十进制值。
我很难将十六进制表示形式作为字符串转换为十六进制,然后将结果转换为十进制。
代码在这里:
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);