如何在字节数组中放置实际表示十六进制值的字符

本文关键字:表示 十六进制 字符 字节 字节数 数组 | 更新日期: 2023-09-27 18:04:34

我有一个字符串text = 0a00...4c617374736e6e41。这个字符串实际上包含十六进制值作为字符。我要做的是进行以下转换,而不需要更改,例如将字符a转换为0x41;

text = 0a...4c617374736e6e41;
--> byte[] bytes = {0x0a, ..., 0x4c, 0x61, 0x73, 0x74, 0x73, 0x6e, 0x6e, 0x41};

这是我到目前为止尝试实现的:

...
string text = "0a00...4c617374736e6e41";
var storage = StringToByteArray(text)
...
Console.ReadKey();
public static byte[] StringToByteArray(string text)
{
    char[] buffer = new char[text.Length/2];
    byte[] bytes = new byte[text.length/2];
    using(StringReader sr = new StringReader(text))
    {
        int c = 0;
        while(c <= text.Length)
        {
            sr.Read(buffer, 0, 2);
            Console.WriteLine(buffer);
            //How do I store the blocks in the byte array in the needed format?
            c +=2;
        }
    }
}

Console.WriteLine(buffer)给了我需要的两个字符。但我不知道如何把它们放在所需的格式。

以下是我已经在主题中找到的一些链接,但是我无法将其转移到我的问题:

  • 我将如何读取十六进制值的ascii字符串在字节数组?
  • 如何将字节数组转换为十六进制字符串,反之亦然?

如何在字节数组中放置实际表示十六进制值的字符

试试这个

            string text = "0a004c617374736e6e41";
            List<byte> output = new List<byte>();
            for (int i = 0; i < text.Length; i += 2)
            {
                output.Add(byte.Parse(text.Substring(i,2), System.Globalization.NumberStyles.HexNumber));
            }