Browse Source

FromHex,优化性能

master
王厅 1 week ago
parent
commit
9ee2b88b23
  1. 13
      Apewer/BytesUtility.cs

13
Apewer/BytesUtility.cs

@ -186,19 +186,18 @@ namespace Apewer
public static byte[] FromHex(this string hex)
{
if (string.IsNullOrEmpty(hex)) return Empty;
hex = hex.Replace(" ", "").Replace("-", "");
if (string.IsNullOrEmpty(hex) || hex.Length < 2) return Empty;
if (hex.Length % 2 != 0) return Empty;
var chars = hex.ToLower().ToCharArray();
chars = chars.FindAll(x => x != ' ' && x != '-');
if (chars.Length < 1 || chars.Length % 2 != 0) return Empty;
var lower = hex.ToLower().ToCharArray();
var half = lower.Length / 2;
var half = chars.Length / 2;
var bytes = new byte[half];
for (var i = 0; i < half; i++)
{
var offset = i * 2;
var h = Constant.HexCollection.IndexOf(lower[offset]);
var l = Constant.HexCollection.IndexOf(lower[offset + 1]);
var h = Constant.HexCollection.IndexOf(chars[offset]);
var l = Constant.HexCollection.IndexOf(chars[offset + 1]);
if (h < 0 || l < 0) return Empty;
bytes[i] = Convert.ToByte((h * 16) + l);
}

Loading…
Cancel
Save