C# 字符串转二进制、二进制转字符串

2022/4/23 17:12:37

本文主要是介绍C# 字符串转二进制、二进制转字符串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/// <summary>
/// 将字符串转成二进制
/// </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>
/// 将二进制转成字符串
/// </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);
}



这篇关于C# 字符串转二进制、二进制转字符串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程