本文介绍了从十六进制字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个字符串位于我收到的字节数组中的数据包中。如果我使用 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;
}

这篇关于从十六进制字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:19