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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM