How decode encoded Base64 to string text?

Simen Kjærås simen.kjaras at gmail.com
Fri Nov 8 13:14:05 UTC 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


More information about the Digitalmars-d-learn mailing list