字符转换类
public class Utils { //byte[]数组转16字符串 public static string ByteToHexStr(byte[] by) { StringBuilder ret = new StringBuilder(); foreach (byte b in by) { //{0:X2} 大写 ret.AppendFormat("{0:X2}" + " ", b); } return ret.ToString(); } //删除字符串里指定的字符 public static string detchar(string str, string c) { int i = str.IndexOf(c); while (i >= 0) { str = str.Remove(i, 1); i = str.IndexOf(c); } return str; } //根据指定的标记符,分隔字符串,并返回字符数组 public static string[] SplitPage(string source, string split) { int len = split.Length; ArrayList al = new ArrayList(); int start = 0; //开始位置 int j = -1; //匹配索引位置 while (true) { j = source.IndexOf(split, start); if (j > -1) { al.Add(source.Substring(start, j - start)); int s = j - start; start = j + len; } else { al.Add(source.Substring(start)); break; } } string[] result; if (al.Count == 0) { string[] r = new string[1]; r[0] = source; result = r; } else { string[] r = new string[al.Count]; for (int i = 0; i < al.Count; i++) { r[i] = al[i].ToString(); } result = r; } return result; } //删除各种括号 public static string[] delstr(string str) { str = detchar(str, "\"");//删除各种符号 str = detchar(str, "{"); str = detchar(str, "}"); str = detchar(str, "["); str = detchar(str, "]"); str = str.Replace("data:", ""); return SplitPage(str, ","); } //16进制字符串转Byte[] public static byte[] hexStringToByte(string hex) { hex = hex.Replace(" ", "");//去掉空格 if (hex.Length % 2 == 1) { hex = hex.Insert(hex.Length - 1, "0"); } byte[] b = new byte[hex.Length / 2]; for (var x = 0; x < b.Length; x++) { var i = Convert.ToInt32(hex.Substring(x * 2, 2), 16); b[x] = (byte)i; } return b; } //十六进制字符串转普通字符串 public static string HexStringToDec(string hex) { return System.Text.Encoding.Default.GetString(hexStringToByte(hex)); } //普通字符串转16进制字符串 public static string DecStringToHex(string dec) { return ByteToHexStr(System.Text.Encoding.Default.GetBytes(dec)); } //将字符串转换成16进制 public static string StrToHex(string s) { StringBuilder result = new StringBuilder(); byte[] arrByte = System.Text.Encoding.GetEncoding("GB18030").GetBytes(s); // byte[] arrByte = System.Text.Encoding.Default.GetBytes(s); for (int i = 0; i < arrByte.Length; i++) { //Convert.ToString(byte, 16)把byte转化成十六进制string result.Append(System.Convert.ToString(arrByte[i], 16).ToUpper().PadLeft(2, '0')); result.Append(" "); } return result.ToString(); } }