.NET-- 常用转换
/// <summary> /// ASCII字符串转10进制 16进制 /// </summary> /// <param name="value">字符串</param> /// <param name="famate">要转换的格式 10 16</param> /// <param name="c">间隔符</param> /// <returns></returns> public static string GetChars(string value, char? c, int? length=2, int famate = 10) { byte[] ba = ASCIIEncoding.Default.GetBytes(value); string res = string.Empty; foreach (var s in ba) { string tempstr = string.Empty; switch (famate) { case 10: tempstr = s.ToString(); break; case 16: tempstr = String.Format("{0:X}", s); break; default: break; } //验证是否需要补0 if (length.HasValue&&length.Value>1) tempstr = tempstr.PadLeft(length.Value, '0'); //验证是否需要添加间隔符 if (c.HasValue) res += tempstr + c.ToString(); else res += tempstr; } return res; }
/// <summary> /// 2 8 6 10 16进制相互转化函数 /// </summary> /// <param name="value"></param> /// <param name="fromBase"></param> /// <param name="toBase"></param> /// <returns></returns> public static string ConvertString(string value, int fromBase, int toBase) { int intValue = Convert.ToInt32(value, fromBase); return Convert.ToString(intValue, toBase); }
/// <summary> ///作用:将16进制数据编码转化为字符串,是Encode的逆过程 /// </summary> /// <param name="strDecode"></param> /// <returns></returns> public static string Decode(string strDecode) { string sResult = ""; for (int i = 0; i < strDecode.Length / 4; i++) { sResult += (char)Int16.Parse(strDecode.Substring(i * 4, 4), NumberStyles.HexNumber); } return sResult; } /// <summary> /// 作用:将字符串内容转化为16进制数据编码,其逆过程是Decode /// 参数说明: /// strEncode 需要转化的原始字符串 /// 转换的过程是直接把字符转换成Unicode字符,比如数字"3"-->0033,汉字"我"-->U+6211 /// 函数decode的过程是encode的逆过程. /// </summary> /// <param name="strEncode"></param> /// <returns></returns> public static string Encode(string strEncode) { string strReturn = "";// 存储转换后的编码 foreach (short shortx in strEncode.ToCharArray()) { strReturn += shortx.ToString("X4"); } return strReturn; }
#region 获取整数的某一位,设置整数的某一位 /// <summary> /// 取整数的某一位 /// </summary> /// <param name="_Resource">要取某一位的整数</param> /// <param name="_Mask">要取的位置索引,自右至左为0-7</param> /// <returns>返回某一位的值(0或者1)</returns> public static int getIntegerSomeBit(int _Resource, int _Mask) { return _Resource >> _Mask & 1; } /// <summary> /// 将整数的某位置为0或1 /// </summary> /// <param name="_Mask">整数的某位</param> /// <param name="a">整数</param> /// <param name="flag">是否置1,TURE表示置1,FALSE表示置0</param> /// <returns>返回修改过的值</returns> public static int setIntegerSomeBit(int _Mask, int a, bool flag) { if (flag) { a |= (0x1 << _Mask); } else { a &= ~(0x1 << _Mask); } return a; } #endregion
/// <summary> /// 2 8 6 10 16进制相互转化函数 /// </summary> /// <param name="value"></param> /// <param name="fromBase"></param> /// <param name="toBase"></param> /// <returns></returns> public static string ConvertString(string value, int fromBase, int toBase) { int intValue = Convert.ToInt32(value, fromBase); return Convert.ToString(intValue, toBase); }