Convert UTF-8 to base64 string
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!
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.