Thread overview
How decode encoded Base64 to string text?
Nov 08, 2019
Marcone
Nov 08, 2019
Aldo
Nov 08, 2019
Marcone
Nov 08, 2019
Simen Kjærås
November 08, 2019
I can encode "Helo World!" to Base64 and get "TWFyY29uZQ==", but if I try to decode "TWFyY29uZQ==" I can not recovery "Helo World!" but [77, 97, 114, 99, 111, 110, 101]. How can I recover "Helo World!" when decode? Thank you.


import std;

void main(){
	string text = "Helo World!";

	auto encoded = Base64.encode(text.representation);
	auto decoded = Base64URL.decode("TWFyY29uZQ==");

	writeln(encoded); // prints: "TWFyY29uZQ=="
	writeln(to!string(decoded)); // prints: [77, 97, 114, 99, 111, 110, 101] but I want to print: "Helo World!"
}
November 08, 2019
On Friday, 8 November 2019 at 11:46:44 UTC, Marcone wrote:
> I can encode "Helo World!" to Base64 and get "TWFyY29uZQ==", but if I try to decode "TWFyY29uZQ==" I can not recovery "Helo World!" but [77, 97, 114, 99, 111, 110, 101]. How can I recover "Helo World!" when decode? Thank you.
>
> ...
> 	writeln(to!string(decoded));
> ...

Casting to string seems to work: writeln(cast(string) decoded);
November 08, 2019
On Friday, 8 November 2019 at 11:46:44 UTC, Marcone wrote:
> I can encode "Helo World!" to Base64 and get "TWFyY29uZQ==", but if I try to decode "TWFyY29uZQ==" I can not recovery "Helo World!" but [77, 97, 114, 99, 111, 110, 101]. How can I recover "Helo World!" when decode? Thank you.
>
>
> import std;
>
> void main(){
> 	string text = "Helo World!";
>
> 	auto encoded = Base64.encode(text.representation);
> 	auto decoded = Base64URL.decode("TWFyY29uZQ==");
>
> 	writeln(encoded); // prints: "TWFyY29uZQ=="
> 	writeln(to!string(decoded)); // prints: [77, 97, 114, 99, 111, 110, 101] but I want to print: "Helo World!"
> }

What Aldo said - Base64 operates on ubyte[], which a string is not (it's immutable(char)[]). There's also assumeUTF (https://dlang.org/library/std/string/assume_utf.html) which may document your code a bit better than a simple cast, but it does the same thing inside.

The reason Base64 operates on ubyte[] is to be able to encode arbitrary data, while the reason to!string doesn't convert your ubyte[] to a readable string is that not all ubyte[] are valid strings, and displaying arbitrary data as if it were a string is sure to cause problems.

--
  Simen
November 08, 2019
On Friday, 8 November 2019 at 12:36:37 UTC, Aldo wrote:
> On Friday, 8 November 2019 at 11:46:44 UTC, Marcone wrote:
>> I can encode "Helo World!" to Base64 and get "TWFyY29uZQ==", but if I try to decode "TWFyY29uZQ==" I can not recovery "Helo World!" but [77, 97, 114, 99, 111, 110, 101]. How can I recover "Helo World!" when decode? Thank you.
>>
>> ...
>> 	writeln(to!string(decoded));
>> ...
>
> Casting to string seems to work: writeln(cast(string) decoded);

Thank you very much! It is working fine!