从十六进制转换为字符串

发布于 2024-07-17 02:19:03 字数 499 浏览 9 评论 0原文

我需要检查以 byte 数组形式收到的数据包内是否存在 string。 如果我使用 BitConverter.ToString(),我会得到带破折号的 string 字节 (fe: 00-50-25-40-A5-FF)。
我尝试了快速谷歌搜索后找到的大多数函数,但大多数函数都有输入参数类型 string ,如果我用带破折号的 string 调用它们,它会抛出异常。

我需要一个将十六进制(作为字符串或作为字节)转换为表示十六进制值的字符串的函数(fe:0x31 = 1) 。 如果输入参数为字符串,则该函数应识别破折号(例如“47-61-74-65-77-61-79-53-65-72-76-65-72”),因为 BitConverter 无法正确转换。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

单挑你×的.吻 2024-07-24 02:19:03

像这样吗?

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;
}

Like so?

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;
}
花落人断肠 2024-07-24 02:19:03

对于 Unicode 支持:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}
╭⌒浅淡时光〆 2024-07-24 02:19:03
string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

您可以在 -
处分割字符串
将文本转换为整数 (int.TryParse)
将 int 输出为十六进制字符串 {0:x2}

string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}

最近可好 2024-07-24 02:19:03
 string hexString = "8E2";
 int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
 Console.WriteLine(num);
 //Output: 2274

来自 https://msdn.microsoft.com/en-us/library/bb311038 .aspx

 string hexString = "8E2";
 int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
 Console.WriteLine(num);
 //Output: 2274

From https://msdn.microsoft.com/en-us/library/bb311038.aspx

献世佛 2024-07-24 02:19:03

您对“0x31 = 1”的引用让我认为您实际上是在尝试将 ASCII 值转换为字符串 - 在这种情况下您应该使用类似 Encoding.ASCII.GetString(Byte[]) 的东西

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

一杯敬自由 2024-07-24 02:19:03

如果您需要将结果作为字节数组,则应该直接传递它,而不将其更改为字符串,然后将其更改回字节。
在您的示例中, (fe: 0x31 = 1) 是 ASCII 代码。 在这种情况下,要将字符串(十六进制值)转换为 ASCII 值,请使用:
Encoding.ASCII.GetString(byte[])

        byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
        string ascii=Encoding.ASCII.GetString(data);
        Console.WriteLine(ascii);

控制台会显示:1234567890

If you need the result as byte array, you should pass it directly without changing it to a string, then change it back to bytes.
In your example the (f.e.: 0x31 = 1) is the ASCII codes. In that case to convert a string (of hex values) to ASCII values use:
Encoding.ASCII.GetString(byte[])

        byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
        string ascii=Encoding.ASCII.GetString(data);
        Console.WriteLine(ascii);

The console will display: 1234567890

情绪少女 2024-07-24 02:19:03

我的 Net 5 解决方案还在末尾处理空字符:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}

My Net 5 solution that also handles null characters at the end:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}
蓝海 2024-07-24 02:19:03

单线:

    var input = "Hallo Hélène and Mr. Hörst";
    var ConvertStringToHexString = (string input) => String.Join("", Encoding.UTF8.GetBytes(input).Select(b => $"{b:X2}"));
    var ConvertHexToString = (string hexInput) => Encoding.UTF8.GetString(Enumerable.Range(0, hexInput.Length / 2).Select(_ => Convert.ToByte(hexInput.Substring(_ * 2, 2), 16)).ToArray());
    Assert.AreEqual(input, ConvertHexToString(ConvertStringToHexString(input)));

One-liners:

    var input = "Hallo Hélène and Mr. Hörst";
    var ConvertStringToHexString = (string input) => String.Join("", Encoding.UTF8.GetBytes(input).Select(b => 
quot;{b:X2}"));
    var ConvertHexToString = (string hexInput) => Encoding.UTF8.GetString(Enumerable.Range(0, hexInput.Length / 2).Select(_ => Convert.ToByte(hexInput.Substring(_ * 2, 2), 16)).ToArray());
    Assert.AreEqual(input, ConvertHexToString(ConvertStringToHexString(input)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文