代码之家  ›  专栏  ›  技术社区  ›  chester89

将.net字符串对象转换为base64编码字符串

  •  33
  • chester89  · 技术社区  · 16 年前

    我有一个问题,在将.NET字符串编码为base64时要使用哪个Unicode编码?我知道字符串在Windows上是UTF-16编码的,那么我的编码方式是正确的吗?

    public static String ToBase64String(this String source) {
            return Convert.ToBase64String(Encoding.Unicode.GetBytes(source));
        }
    
    4 回复  |  直到 16 年前
        1
  •  26
  •   Adam Robinson    16 年前

    你所提供的是完全实用的。它将生成一个base64编码的字符串,其中包含用UTF-16编码的源字符串的字节。

        2
  •  3
  •   Alan Moore Chris Ballance    16 年前

    要知道你不知道 使用UTF-16仅仅因为那是.NET字符串所使用的。当您创建字节数组时,您可以自由选择将处理字符串中所有字符的任何编码。例如,如果文本是基于拉丁语的语言,UTF-8会更有效,但它仍然可以处理所有已知字符。

        3
  •  3
  •   DareDevil    12 年前

    这里是解决方案,我已经转换了一个随机字符串转换,就像你可以给任何大小10,Base64将输出。

    //This function will return a random string from the given numeric characters
    public string RandomString(int size)
    {
    const string legalCharacters = "1234567890";
    Random random = new Random();
    StringBuilder builder = new StringBuilder();
    char ch = '\0';
    
    for (int i = 0; i <= size - 1; i++) {
        ch = legalCharacters(random.Next(0, legalCharacters.Length));
        builder.Append(ch);
    }
    return builder.ToString();
    }
    public const string BASE64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
    public string DecToBase64(long lVal)
    {
    string sVal = null;
    sVal = "";
    while (lVal >= 64) {
        sVal = sVal + DecToBase64(lVal / 64);
        lVal = lVal - 64 * (lVal / 64);
    }
    sVal = sVal + Strings.Mid(BASE64, Convert.ToInt32(lVal) + 1, 1);
    return sVal;
    }
    
    //here is how we can have result in variable:
    string Base64 = "";
    Base64 = DecToBase64(RandomString(10)); //this will produce a combination up-to length of 10
    
        4
  •  2
  •   abatishchev Karl Johan    16 年前

    MSDN 证实了这一点 UnicodeEncoding 类表示 UTF-16 Unicode字符的编码。

    推荐文章