连接两个Base64字符串,然后对其进行解码 [英] Join two Base64 strings and then decode them

查看:146
本文介绍了连接两个Base64字符串,然后对其进行解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何将两个编码为Base64的字符串连接起来,然后进行解码并获得组合结果.

I'm trying to figure out how to join two strings that are encoded Base64 and then decode and get the combined result.

示例:

string1您好--string1 Base64 SGVsbG8 =

string1 Hello --- string1 Base64 SGVsbG8=

string2世界--string2 Base64 V29ybGQ =

string2 World --- string2 Base64 V29ybGQ=

如果我加入base64,我得到的东西将不会解码SGVsbG8 = V29ybGQ =

If I join the base64 I get something that wont decode SGVsbG8=V29ybGQ=

我希望结果说:Hello World

I want the result to say: Hello World

我不希望仅此示例工作,而是希望任何字符串均可工作. 这是一个非常简化的问题,是我要编写的应用程序中遇到的问题的一个步骤.

I don't want only this example to work but rather something that will work with any string. This is a very simplified problem which is a step on an application I'm trying to write I'm stuck on.

推荐答案

我找到了一种最佳方法,在一个字符串和另一个字符串之间加上加号,然后加上一个,并且在该字符串中只有一个等于char('=').字符串的结尾.返回值将为"Hello> World",然后删除>":

I found a best way to do this, add plus between one string and other, and add ONE, and only ONE equals char ('=') at the end of string. The return will be "Hello>World", then remove the ">":

class Program
{
    static void Main(string[] args)
    {
        string base64String = "SGVsbG8+V29ybGQ=";
        byte[] encodedByte = Convert.FromBase64String(base64String);
        var finalString = Encoding.Default.GetString(encodedByte)).Replace(">", " ");
        Console.WriteLine(finalString.ToString());
    }
 }

(旧方法)在C#中,我做这样的事情:

(Old way) In C# I do something like this:

class Program
{
    static void Main(string[] args)
    {
        string base64String = "SGVsbG8=V29ybGQ=";
        Console.WriteLine(DecodeBase64String(base64String));
        Console.ReadLine();
    }

    public static string DecodeBase64String(string base64String)
    {
        StringBuilder finalString = new StringBuilder();

        foreach (var text in base64String.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
        {
            byte[] encodedByte = Convert.FromBase64String(text + "=");

            finalString.Append(Encoding.Default.GetString(encodedByte));
            finalString.Append(" "); //This line exists only to attend the "Hello World" case. The correct is remove this and let the one that will receive the return to decide what will do with returned string.
        }

        return finalString.ToString();
    }
}

这篇关于连接两个Base64字符串,然后对其进行解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆