欢迎访问!
您的支持是我们不断前行的动力!

C# Byte[]转字符串,字符串转Byte[],字符串转Unicode,Unicode转字符串,Unicode转中文

using System;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// 将字节数组转为字符串
/// </summary>
/// <param name="b">字节数组</param>
/// <param name="e">编码,默认为Default</param>
/// <returns></returns>
internal static string ByteToString(byte[] b, Encoding e = null)
{
    if (e == null)
    {
        e = Encoding.Default;
    }
    string result = e.GetString(b);
    return result;
}

/// <summary>
/// 将字符串转为字节数组
/// </summary>
/// <param name="s">字符串</param>
/// <param name="e">编码,默认为Default</param>
/// <returns></returns>
internal static byte[] StringToByte(string s, Encoding e = null)
{
    if (e == null)
    {
        e = Encoding.Default;
    }
    byte[] b = e.GetBytes(s);
    return b;
}

/// <summary>
/// 字符串转Unicode码
/// </summary>
/// <returns>Unicode码</returns>
/// <param name="value">字符串</param>
internal static string StringToUnicode(string value)
{
    byte[] bytes = Encoding.Unicode.GetBytes(value);
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < bytes.Length; i += 2)
    {
        // 取两个字符,每个字符都是右对齐。
        stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
    }
    return stringBuilder.ToString();
}

/// <summary>
/// Unicode转String
/// </summary>
/// <param name="SourceString"></param>
/// <returns></returns>
internal static string UnicodeToString(string SourceString)
{
    Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
    return reg.Replace(SourceString, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
}

/// <summary>
/// Unicode转中文
/// </summary>
/// <returns>中文</returns>
/// <param name="text">Unicode码</param>
internal static string UnicodeToChinese(string text)
{
    MatchCollection mc = Regex.Matches(text, "\\\\u([\\w]{4})");
    if (mc != null && mc.Count > 0)
    {
        foreach (Match m2 in mc)
        {
            string v = m2.Value;
            string word = v.Substring(2);
            byte[] codes = new byte[2];
            int code = Convert.ToInt32(word.Substring(0, 2), 16);
            int code2 = Convert.ToInt32(word.Substring(2), 16);
            codes[0] = (byte)code2;
            codes[1] = (byte)code;
            text = text.Replace(v, Encoding.Unicode.GetString(codes));
        }
    }
    return text;
}

 

赞(0) 打赏
转载请注明出处,未注明出处不得转载,蜘蛛侠 » C# Byte[]转字符串,字符串转Byte[],字符串转Unicode,Unicode转字符串,Unicode转中文
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

蜘蛛侠,您身边的爬虫专家!

觉得文章有用就打赏一下文章作者吧

支付宝扫一扫打赏

微信扫一扫打赏