我需要检查一个 string
位于我收到的数据包中作为 byte
数组。如果我使用 BitConverter.ToString()
,我得到的字节是 string
和破折号(例如:00-50-25-40-A5-FF)。
我尝试了快速谷歌搜索后发现的大多数函数,但大多数函数都有输入参数类型 string
,如果我用带有破折号的 string
调用它们,它会抛出异常。
我需要一个函数,将十六进制(如 string
或 byte
)转换为表示十六进制值(例如:0x31)的 string
= 1).如果输入参数是string
,函数应该识别破折号(例如“47-61-74-65-77-61-79-53-65-72-76-65-72”),因为 BitConverter
没有正确转换。
最佳答案
像这样吗?
static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
关于c# - 从十六进制转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/724862/