C# 字符串转16进制,16进制转Base64 哈哈哈 uf65/rn+
测试:
哈哈哈 uf65/rn+
场景描述:
对接java接口,字符串转16进制再转base64;遇到转换不一样问题;后来定位对方编码格式不对;
测试代码:
string str = "哈哈哈abcABC123";
///字符串转换Base64
string sendStr =GetJavaBase64ByStr(str);
//Base64转字符串
string resStr = GetStrByGetJavaBase64Str(sendStr);
封装代码如下:
#region 对接java接口 Base64转换string字符串 /// <summary> /// 逆向转换(java接口Base64转换string字符串) /// </summary> /// <param name="base64Str"></param> /// <returns></returns> public static string GetStrByGetJavaBase64Str(string base64Str) { string hexStr = GetHexStrByBase64Str(base64Str); string resStr = GetStrByHexStr(hexStr); return resStr; } /// <summary> /// 16进制字符串转字符串 /// </summary> /// <param name="hexStr"></param> /// <returns></returns> public static string GetStrByHexStr(string hexStr) { byte[] buf1 = new byte[hexStr.Length / 2]; for (int i = 0; i < hexStr.Length; i += 2) { // 将 16进制字符串 中的每两个字符转换成 byte,并加入到新申请的 byte数组 中 buf1[i / 2] = Convert.ToByte(hexStr.Substring(i, 2), 16); } // 将 byte数组 解码成 字符串: //string resStr = Encoding.Default.GetString(buf1); string resStr = Encoding.GetEncoding("GB18030").GetString(buf1); return resStr; } /// <summary> /// Base64字符串转16进制字符串 /// </summary> /// <param name="basestr"></param> /// <returns></returns> public static string GetHexStrByBase64Str(string base64Str) { try { byte[] bytes = System.Convert.FromBase64String(base64Str); //return byteToHexStr(bytes); string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("X2"); } } return returnStr; } catch (FormatException ex) { //转换失败 return null; } } #endregion 对接java接口 Base64转换string字符串 #region 对接java接口 string字符串转换Base64 public static string GetJavaBase64ByStr(string str) { string strHex = GetHexByString(str, Encoding.GetEncoding("GB18030")); string resStr = GetBase64By16Str(strHex); return resStr; } /// <summary> /// 字符串转16进制通过 /// </summary> /// <param name="str"></param> /// <param name="encode"></param> /// <returns></returns> public static string GetHexByString(string str, Encoding encode) { 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; } } #endregion