public static class Helper
{
public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
public static string ToHex(this IEnumerable<byte> array)
{
StringBuilder s = new StringBuilder();
foreach (var v in array)
s.Append(HexTbl[v]);
return s.ToString();
}
public static string ToHex(this byte[] array)
{
StringBuilder s = new StringBuilder(array.Length*2);
foreach (var v in array)
s.Append(HexTbl[v]);
return s.ToString();
}
}
public static class ExtensionMethods {
public static string ToHex(this byte[] data) {
return ToHex(data, "");
}
public static string ToHex(this byte[] data, string prefix) {
char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int i = 0, p = prefix.Length, l = data.Length;
char[] c = new char[l * 2 + p];
byte d;
for(; i < p; ++i) c[i] = prefix[i];
i = -1;
--l;
--p;
while(i < l) {
d = data[++i];
c[++p] = lookup[d >> 4];
c[++p] = lookup[d & 0xF];
}
return new string(c, 0, c.Length);
}
public static byte[] FromHex(this string str) {
return FromHex(str, 0, 0, 0);
}
public static byte[] FromHex(this string str, int offset, int step) {
return FromHex(str, offset, step, 0);
}
public static byte[] FromHex(this string str, int offset, int step, int tail) {
byte[] b = new byte[(str.Length - offset - tail + step) / (2 + step)];
byte c1, c2;
int l = str.Length - tail;
int s = step + 1;
for(int y = 0, x = offset; x < l; ++y, x += s) {
c1 = (byte)str[x];
if(c1 > 0x60) c1 -= 0x57;
else if(c1 > 0x40) c1 -= 0x37;
else c1 -= 0x30;
c2 = (byte)str[++x];
if(c2 > 0x60) c2 -= 0x57;
else if(c2 > 0x40) c2 -= 0x37;
else c2 -= 0x30;
b[y] = (byte)((c1 << 4) + c2);
}
return b;
}
}
在上面的速度测试中击败所有其他人:
===长串测试
BitConvertReplace计算Time Elapsed 2415 ms . BitConvertReplace计算时间
StringBuilder计算Time Elapsed 5668 ms
LinqConcat计算时间流逝11826 ms . LinqConcat计算时间流逝11826 ms . LinqConcat计算时间流逝11826 ms
LinqJoin计算Time Elapsed 9323 ms .使用实例
LinqAgg计算Time Elapsed 7444 ms .使用实例
ToHexTable calculation Time Elapsed 1028 ms .使用实例
ToHexAcidzombie计算Time Elapsed 1035 ms . sh
ToHexPatrick计算时间流逝814毫秒
ToHexKurt计算Time Elapsed 1604 ms
ByteArrayToHexString计算Time Elapsed 1330 ms
. ByteArrayToHexString计算时间
===许多字符串测试
BitConvertReplace计算Time Elapsed 2238 ms . BitConvertReplace计算时间
StringBuilder计算Time Elapsed 5393 ms
LinqConcat calculation Time Elapsed 9043 ms .使用实例
LinqJoin计算Time Elapsed 9131 ms .使用实例
LinqAgg计算Time Elapsed 7324 ms .使用实例
ToHexTable calculation Time Elapsed 968 ms .使用实例
ToHexAcidzombie calculation Time Elapsed 969 ms . ToHexAcidzombie计算时间
ToHexPatrick计算时间流逝956毫秒
ToHexKurt计算Time Elapsed 1547 ms
ByteArrayToHexString计算Time Elapsed 1277 ms