/
EncodingHelper.cs
60 lines (55 loc) · 1.77 KB
/
EncodingHelper.cs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Text;
namespace YiSha.Util
{
public class EncodingHelper
{
private static string HexStr = "0123456789abcdef";
private static char[] HexCharArr = HexStr.ToCharArray();
public static string ByteArrToHex(byte[] btArr)
{
char[] strArr = new char[btArr.Length * 2];
int i = 0;
foreach (byte bt in btArr)
{
strArr[i++] = HexCharArr[bt >> 4 & 0xf];
strArr[i++] = HexCharArr[bt & 0xf];
}
return new string(strArr);
}
public static byte[] HexToByteArr(string hexStr)
{
char[] charArr = hexStr.ToCharArray();
byte[] btArr = new byte[charArr.Length / 2];
int index = 0;
for (int i = 0; i < charArr.Length; i++)
{
int highBit = HexStr.IndexOf(charArr[i]);
int lowBit = HexStr.IndexOf(charArr[++i]);
btArr[index] = (byte)(highBit << 4 | lowBit);
index++;
}
return btArr;
}
public static string ByteArrToHexDefault(byte[] btArr)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in btArr)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
public static byte[] HexToByteArrDefault(string hexStr)
{
byte[] inputArr = new byte[hexStr.Length / 2];
for (int i = 0; i < hexStr.Length / 2; i++)
{
int v = Convert.ToInt32(hexStr.Substring(i * 2, 2), 16);
inputArr[i] = (byte)v;
}
return inputArr;
}
}
}