C#⼆进制与字符串互转换,⼗六进制转换为字符串、float、int /// <summary>    /// 将字符串转成⼆进制 “10011100000000011100011111111101”
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string bianma(string s)    {
byte[] data = Encoding.Unicode.GetBytes(s);
StringBuilder result = new StringBuilder(data.Length * 8);
foreach (byte b in data)
  {
    result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
  }
return result.ToString();
}
/// <summary>
/// 将⼆进制 “10011100000000011100011111111101” 转成字符串
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string jiema(string s)    {
System.Text.RegularExpressions.CaptureCollection cs =  System.Text.RegularExpressions.Regex.Match(s, @"([01]
{8})+").Groups[1].Captures;
byte[] data = new byte[cs.Count];
for (int i = 0; i < cs.Count; i++)
{
  data[i] = Convert.ToByte(cs[i].Value, 2);
}
return Encoding.Unicode.GetString(data, 0, data.Length);
}
/// <summary>
/// <;函数:Decode>
///作⽤:将16进制数据编码转化为字符串
/// </summary>
/// <param name="strDecode"></param>
/
// <returns></returns>
public string DecodeToString(string strDecode)
{
string sResult = "";
for (int i = 0; i < strDecode.Length / 4; i++)
{
  sResult += int.Parse(strDecode.Substring(i * 4, 4), global::System.Globalization.NumberStyles.HexNumber);            }
  return sResult;
}
/// <summary>
/// 将16进制数转为10进制数,并保留⼩数位数
/// </summary>
/// <param name="strDecode"></param>
/// <param name="i"></param>
/// <returns></returns>
二进制与十六进制的转换表public float DecodeToFloat(string strDecode, int i)
{
  int num = Convert.ToInt32(strDecode, 16);
  float result = (float.Parse(num.ToString())) / i;
  return result;
}
/// <summary>
/
// 将16进制数转为10进制数整型
/// </summary>
/// <param name="strDecode"></param>
/// <returns></returns>
public int DecodeToInt(string strDecode)
{
  int result = Convert.ToInt32(strDecode, 16);
  return result;
}
/// <summary>
/// 获取数据源(读取记事本)
/
// </summary>
/// <returns></returns>
public string GetData()
{
string effectiveData = "0";//有效数据
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));                string strText = "";
while (true){
string strTemp = sr.ReadLine();
if (strTemp != null)
{
strText += strTemp;
continue;
}
else
{
break;
}
}
strText = strText.Trim();
sr.Close();
fs.Close();
return effectiveData;
}
/// <summary>
/// 清空记事本内容
/// </summary>
public void ClearText()
{
//StreamWriter sw = new StreamWriter(filePath, false);
//sw.Write(string.Empty);
/
/sw.Close();
//sw.Dispose();
FileStream fs = new FileStream(filePath, FileMode.Create);
fs.Close();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。