Last active
January 1, 2016 00:29
-
-
Save Wind4/8066756 to your computer and use it in GitHub Desktop.
byte[] 转 string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// 十六进制映射表 | |
/// </summary> | |
private static readonly Char[] _lookup = new Char[] | |
{ | |
'0', '1', '2', '3', | |
'4', '5', '6', '7', | |
'8', '9', 'A', 'B', | |
'C', 'D', 'E', 'F' | |
}; | |
/// <summary> | |
/// 将byte数组转换成十六进制字符串 | |
/// </summary> | |
/// <param name="arr"></param> | |
/// <returns></returns> | |
public static String ToHex(Byte[] arr) | |
{ | |
Char[] chars = new Char[arr.Length * 2]; | |
for (int i = 0; i < arr.Length; i++) | |
{ | |
Byte c = arr[i]; | |
chars[i * 2] = _lookup[(c >> 4) & 0x0F]; | |
chars[i * 2 + 1] = _lookup[c & 0x0F]; | |
} | |
return new String(chars, 0, chars.Length); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly sbyte[] _lookup = new sbyte[] { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }; | |
public static unsafe string ToHex(this byte[] arr) | |
{ | |
int len = arr.Length; | |
int i = 0; | |
sbyte* chars = stackalloc sbyte[len * 2]; | |
fixed (byte* pSrc = arr) | |
{ | |
byte* pIn = pSrc; | |
sbyte* pOut = chars; | |
while (i++ < len) | |
{ | |
*pOut++ = _lookup[*pIn >> 4]; | |
*pOut++ = _lookup[*pIn++ & 0xF]; | |
} | |
} | |
return new String(chars, 0, len * 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment