如何将字符串中的数字转换为十六进制值?

How to convert from numbers in string to its hexadecimal value?

我有一个文本文件(test.txt),里面有十六进制数据,当我打开它时,它看起来像:

test.txt:
00 FF 0F 00 ...等等

我用 .NET 阅读了它们:

byte [] in = System.IO.File.ReadAllBytes("D:/test.txt");

此时,我可以看到我的字符串为:

in[0] = 0x30 // first 0 in[1] = 0x30 // second 0 in[2] = 0x20 // space in[3] = 0x46 // F char ...

我可以删除每个 space 和 \n\r 字符,但我希望对 0x30 到 0x0 和 0x46 到 0xF 进行简单的一行转换

用于转换字符串的单行解决方案:

string s = 00FF10byte [] a = 0x0, 0xFF, 0x10

string 形式读取文件内容,将其拆分,然后将每个部分解析为字节。

为了简单起见,没有输入验证的示例:

var bytes = "00 FF 0F 00"
    .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => byte.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier))
    .ToArray();