Convert UTF-8 to base64 string

C#EncodingUtf 8Base64

C# Problem Overview


I'm trying to convert UTF-8 to base64 string.

Example: I have "abcdef==" in UTF-8. It's in fact a "representation" of a base64 string.

How can I retrieve a "abcdef==" base64 string (note that I don't want a "abcdef==" "translation" from UTF-8, I want to get a string encoded in base64 which is "abcdef==").

EDIT
As my question seems to be unclear, here is a reformulation:

My byte array (let's say I name it A) is represented by a base64 string. Converting A to base64 gives me "abcdef==".

This string representation is sent through a socket in UTF-8 (note that the string representation is exactly the same in UTF-8 and base64). So I receive an UTF-8 message which contains "whatever/abcdef==/whatever" in UTF-8.

So I need to retrieve the base64 "abcedf==" string from this socket message in order to get A.

I hope this is more clear!

C# Solutions


Solution 1 - C#

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicolas VoronView Question on Stackoverflow
Solution 1 - C#IridiumView Answer on Stackoverflow