方法来自 stackoverflow,注释中标明了具体的代码出处位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* the following methods have high performance and come from: http://stackoverflow.com/a/24343727/2753545 */

private static readonly uint[] _lookup32 = CreateLookup32();

private static uint[] CreateLookup32()
{
var result = new uint[256];
for (int i = 0; i < 256; i++)
{
string s = i.ToString("X2");
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}

public static string ByteArrayToHexViaLookup32(byte[] bytes)
{
uint[] lookup32 = _lookup32;
char[] result = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
uint val = lookup32[bytes[i]];
result[2 * i] = (char)val;
result[2 * i + 1] = (char)(val >> 16);
}
return new string(result);
}

// this method is from http://stackoverflow.com/a/17923942/2753545
public static byte[] HexToByteUsingByteManipulation(string s)
{
byte[] bytes = new byte[s.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
int hi = s[i * 2] - 65;
hi = hi + 10 + ((hi >> 31) & 7);

int lo = s[i * 2 + 1] - 65;
lo = lo + 10 + ((lo >> 31) & 7) & 0x0f;

bytes[i] = (byte)(lo | hi << 4);
}
return bytes;
}

留言

2016-10-12