十六进制字符串转换
/// 十六进制转换字符串 /// </summary> /// <param name="bts"></param> /// <param name="startIndex"></param> /// <param name="lenth"></param> /// <returns></returns> public string ByteArrayToHexString(byte[] bts) { if (bts == null || bts.Length == 0) return string.Empty; return ByteArrayToHexString(bts, 0, bts.Length); } public string ByteArrayToHexString(byte[] bts, int startIndex, int lenth) { if (bts == null || lenth == 0) return string.Empty; StringBuilder sb = new StringBuilder(); for (int ii = startIndex; ii < bts.Length && ii < startIndex + lenth; ii++) { string sh = bts[ii].ToString("X").PadLeft(2, '0'); sb.Append(sh + " "); } returnsb.ToString(); }
/// <summary> /// 字符串转换十六进制 /// </summary> /// <param name="hexStr"></param> /// <param name="bts"></param> /// <returns></returns> public bool ByteArrayFromHexString(string hexStr, out byte[] bts) { try { hexStr = hexStr.Trim(); string[] ss = hexStr.Split(new char[] { ' ', ',', ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); bts = new byte[ss.Length]; for (int ii = 0; ii < ss.Length; ii++) { bts[ii] = byte.Parse(ss[ii], System.Globalization.NumberStyles.HexNumber); } return true; } catch { bts = null; return false; } }