问题描述
我需要检查一个字符串
位于我收到的字节
数组中的数据包中。如果我使用 BitConverter.ToString()
,我得到的字节字符串
用破折号(FE:00-50- 25-40-A5-FF)。结果
我想我一个快速的谷歌搜索后,发现大部分功能,但大多有输入参数类型字符串
,如果我给他们打电话与字符串
与破折号,它抛出一个异常。
I need to check for a string
located inside a packet that I receive as byte
array. If I use BitConverter.ToString()
, I get the bytes as string
with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type string
and if I call them with the string
with dashes, It throws an exception.
我需要,变成十六进制的函数(如字符串
或字节
)到字符串
的再presents的十六进制值(FE:0X31 = 1)。如果输入参数为字符串
,功能应该承认破折号(例如47-61-74-65-77-61-79-53-65-72-76- 65-72),因为 BitConverter
不正确转换。
I need a function that turns hex(as string
or as byte
) into the string
that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is string
, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because BitConverter
doesn't convert correctly.
推荐答案
像这样?
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;
}
这篇关于从十六进制字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!