我们可以转换十六进制字符串到一个字节数组使用内置函数在c#或我必须为此做一个自定义方法?
这里有一个很有趣的LINQ示例。
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
下面的代码通过逐字节解析字符串,将十六进制字符串更改为字节数组。
public static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
我做了些研究,找到了那个字节。Parse甚至比Convert.ToByte还要慢。 我能想到的最快的转换大约每字节使用15个刻度。
public static byte[] StringToByteArrayFastest(string hex) {
if (hex.Length % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
public static int GetHexVal(char hex) {
int val = (int)hex;
//For uppercase A-F letters:
//return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
//也适用于。net Micro Framework,其中(在SDK4.3中)bytes . parse (string)只允许整数格式。
我想这可能有用。
public static byte[] StrToByteArray(string str)
{
Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
for (int i = 0; i <= 255; i++)
hexindex.Add(i.ToString("X2"), (byte)i);
List<byte> hexres = new List<byte>();
for (int i = 0; i < str.Length; i += 2)
hexres.Add(hexindex[str.Substring(i, 2)]);
return hexres.ToArray();
}
推荐文章
- 如何获取HttpContext。目前在ASP。网络核心?
- 给定文件系统路径,是否有一种更短的方法来提取没有扩展名的文件名?
- 方法在字典中添加新项或更新现有项
- 使用Lambda/Linq对列表进行对象排序
- 为什么我不能在.NET中定义一个结构的默认构造函数?
- cmd.exe使用的编码/代码页是什么?
- TypeLoadException表示“没有实现”,但它已经实现了
- 如何在ASP中返回当前操作。NET MVC视图?
- 存储Kinect 2.0版本的动作到BVH文件
- 获取Windows中文件的编码
- SortedList和SortedDictionary之间的区别是什么?
- jQuery用户界面对话框。NET按钮回发
- 合并。net中的两个数组
- 如何在Visual Studio中启用NuGet包恢复?
- 如何在实体框架6中调用存储过程(代码优先)?