static string ByteArrayToString1(byte[] source) { StringBuilder sb = new StringBuilder(); foreach (byte item in source) { sb.AppendFormat("{0:x2}", item); } return sb.ToString(); } static string ByteArrayToString2(byte[] source) { return BitConverter.ToString(source).Replace("-", ""); } static string ByteArrayToString3(byte[] source) { // namespace: System.Runtime.Remoting.Metadata.W3cXsd2001 return new SoapHexBinary(source).ToString(); } static string ByteArrayToString4(byte[] source) { // works for .Net 4 only return String.Concat(Array.ConvertAll(source, x => x.ToString("X2"))); }
Performance:
hex string to byte[]:
static byte[] StringToByteArray1(string source) { return SoapHexBinary.Parse(source).Value; } static byte[] StringToByteArray2(string source) { int sourceLength = source.Length; byte[] result = new byte[sourceLength / 2]; for (int i = 0; i < sourceLength; i += 2) result[i / 2] = Convert.ToByte(source.Substring(i, 2), 16); return result; }
Performance:
Reference: How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
No comments:
Post a Comment