测试:
哈哈哈 uf65/rn+
场景描述:
对接java接口,字符串转16进制再转base64;遇到转换不一样问题;后来定位对方编码格式不对;
private void Test() { string str = "哈哈哈"; str = GetHexByString(str, Encoding.GetEncoding("GB18030"));//Encoding.GetEncoding("GBK") string eee = GetBase64By16Str(str); } /// <summary> /// 字符串转16进制通过 /// </summary> /// <param name="str"></param> /// <param name="encode"></param> /// <returns></returns> public string GetHexByString(string str, Encoding encode)//StringToHexString { byte[] b = encode.GetBytes(str); StringBuilder result = new StringBuilder(); for (int i = 0; i < b.Length; i++) { result.Append(Convert.ToString(b[i], 16)); } return result.ToString(); } /// <summary> /// 字符串转Base64 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetBase64By16Str(string str) { try { System.Text.RegularExpressions.MatchCollection mc = Regex.Matches(str.ToString().ToUpper(), "[a-fA-F0-9]{2}"); byte[] bytes = new byte[mc.Count]; for (int i = 0; i < mc.Count; i++) { bytes[i] = byte.Parse(mc[i].Value, System.Globalization.NumberStyles.HexNumber); } string res = Convert.ToBase64String(bytes); //解决特殊编码问题 //res = System.Web.HttpUtility.UrlEncode(res); //string res =res.Replace("%", "").Replace(",", "").Replace(" ", "+"); return res; } catch (FormatException) { //转换失败 return null; } }
标签:string,uf65,16,res,str,byte,进制 From: https://www.cnblogs.com/yuanshuo/p/17724911.html