要么:
public static string ByteArrayToString(byte[] ba){ StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString();}要么:
public static string ByteArrayToString(byte[] ba){ return BitConverter.ToString(ba).Replace("-","");}例如,这里还有更多的变体。
反向转换将如下所示:
public static byte[] StringToByteArray(String hex){ int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes;}Substring与结合使用是最佳选择
Convert.ToByte。有关更多信息,请参见此答案。如果需要更好的性能,则必须先避免
Convert.ToByte后再放下
SubString。



