Base64 encode data: Difference between revisions

added RPL
(added RPL)
 
(33 intermediate revisions by 23 users not shown)
Line 5:
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">DATA: li_client TYPE REF TO if_http_client,
lv_encoded TYPE string,
lv_data TYPE xstring.
Line 32:
ENDWHILE.
WRITE: / lv_encoded.
</syntaxhighlight>
</lang>
 
{{out}}
Line 39:
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
 
PROC Encode(BYTE ARRAY buf BYTE len CHAR ARRAY res)
CHAR ARRAY chars(65)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
BYTE b
 
res(0)=4
b=buf(0) RSH 2
res(1)=chars(b+1)
 
b=(buf(0)&$03) LSH 4
b==%buf(1) RSH 4
res(2)=chars(b+1)
 
IF len<2 THEN
res(3)='=
ELSE
b=(buf(1)&$0F) LSH 2
b==%buf(2) RSH 6
res(3)=chars(b+1)
FI
 
IF len<3 THEN
res(4)='=
ELSE
b=buf(2)&$3F
res(4)=chars(b+1)
FI
RETURN
 
PROC EncodeFile(CHAR ARRAY fname)
DEFINE BUFLEN="3"
BYTE dev=[1],len
BYTE ARRAY buf(BUFLEN)
CHAR ARRAY res(5)
 
Close(dev)
Open(dev,fname,4)
DO
buf(1)=0 buf(2)=0
len=Bget(dev,buf,BUFLEN)
IF len=0 THEN EXIT FI
 
Encode(buf,len,res)
Print(res)
OD
Close(dev)
RETURN
 
PROC Main()
EncodeFile("H1:FAVICON.ICO")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Base64_encode_data.png Screenshot from Atari 8-bit computer]
<pre>
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
...
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
</pre>
 
=={{header|Ada}}==
{{libheader|AWS}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
with AWS.Response;
Line 56 ⟶ 119:
begin
Ada.Text_IO.Put_Line (Icon_64);
end Encode_AWS;</langsyntaxhighlight>
 
{{out}}
Line 67 ⟶ 130:
=={{header|ALGOL 68}}==
This program is run on a modified Algol 68 Genie 2.8. That interpreter has some bugs, so it does not do binary tcp/ip requests, and I made patches/bugfixes to it in order to run this task.
<langsyntaxhighlight lang="algol68">
STRING codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[@0];
 
Line 131 ⟶ 194:
STRING encoded icon = base64_encode (rosettacode icon);
print ((encoded icon, new line))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 141 ⟶ 204:
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
.section .rodata
ch64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Line 308 ⟶ 371:
mov r0, #0
swi #0
</syntaxhighlight>
</lang>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<lang bacon>CONST file$ = "favicon.ico"
<syntaxhighlight lang="bacon">CONST file$ = "favicon.ico"
binary = BLOAD(file$)
PRINT B64ENC$(binary, FILELEN(file$))
FREE binary</langsyntaxhighlight>
{{out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAE.......QAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
Line 321 ⟶ 385:
===libresolv===
{{libheader|libresolv}} (libresolv is included on most Unix-like systems)
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <resolv.h>
Line 359 ⟶ 423:
 
return 0;
}</langsyntaxhighlight>
Compile with
<pre>gcc -lresolv -o base64encode base64encode.c</pre>
Line 365 ⟶ 429:
===Manual implementation===
The following reads standard input and writes base64-encoded stream to standard output, e.g. <tt>./a.out <some_random_file >/dev/null</tt> if you don't want to see the output. It gives identical output as the common <tt>base64</tt> utility program, though much less efficiently.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <unistd.h>
 
Line 395 ⟶ 459:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">namespace RosettaCode.Base64EncodeData
{
using System;
Line 419 ⟶ 483:
}
}
}</langsyntaxhighlight>
Output:
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <fstream>
Line 481 ⟶ 545:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 494 ⟶ 558:
Assumes the source file is a PRG on disk drive device 8, writes encoded file both to a SEQ file on the same disk and to the screen (where it looks good in 80-column mode on a PET or C128, a little less so on a C64 or VIC). This is all done in PETSCII; transfer out of Commodore-land will require translation of the Base64-encoded file into ASCII.
 
<langsyntaxhighlight lang="basic">
100 print chr$(247);chr$(14);
110 dim a$(63): rem alphabet
Line 532 ⟶ 596:
450 print "error:"st
460 open 15,8,15:input#15,ds,ds$,a,b:close15
470 print ds,ds$,a,b</langsyntaxhighlight>
 
{{Out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/ ...</pre>CwAAmKScAam1rAOPm5ACgo6EA
...
AOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA/////wAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|Common Lisp}}==
Line 542 ⟶ 610:
A nice example for the CL eco system using [http://quickdocs.org/cl-base64/ cl-base64] and [https://www.cliki.net/Drakma drakma].
<langsyntaxhighlight lang="lisp">(eval-when (:load-toplevel :compile-toplevel :execute)
(ql:quickload "drakma")
(ql:quickload "cl-base64"))
Line 563 ⟶ 631:
finally (return (usb8-array-to-base64-string array)))))
(close input)
output))</langsyntaxhighlight>
{{out}}
<pre>"AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///...</pre>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">
require "http/client"
require "base64"
Line 576 ⟶ 644:
Base64.encode(response.body, STDOUT)
end
</syntaxhighlight>
</lang>
 
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.base64, std.net.curl, std.string;
 
const f = "http://rosettacode.org/favicon.ico".get.representation;
Base64.encode(f).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAwqgIAADCjgUAACgAAAAQAAAAIAA...
Line 591 ⟶ 659:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program Base64EncodeData;
{$APPTYPE CONSOLE}
uses IdHTTP, IdCoderMIME;
Line 606 ⟶ 674:
lHTTP.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">data = File.read!("favicon.ico")
encoded = :base64.encode(data)
IO.puts encoded</langsyntaxhighlight>
 
{{out}}
Line 621 ⟶ 689:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(base64demo).
-export([main/0]).
 
Line 631 ⟶ 699:
%% Demonstrating with the library function.
encode_library(Data) ->
base64:encode(Data).</langsyntaxhighlight>
 
{{out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4F...AAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|F_Sharp|F#}}==
===Standard Library===
{{works with|fsharp|4.5}}
<langsyntaxhighlight lang="fsharp">open System
open System.Net
 
Line 651 ⟶ 719:
let encoded = Convert.ToBase64String raw
 
printfn "%s" encoded</langsyntaxhighlight>
 
{{out}}
Line 658 ⟶ 726:
===Manual Implementation===
{{works with|fsharp|4.5}}
<langsyntaxhighlight lang="fsharp">open System.Net
 
let encode s =
Line 688 ⟶ 756:
 
printfn "%s" encoded
</syntaxhighlight>
</lang>
 
{{out}}
Line 694 ⟶ 762:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: base64 http.client io kernel strings ;
 
"http://rosettacode.org/favicon.ico" http-get nip
>base64-lines >string print</langsyntaxhighlight>
{{out}}
<pre>
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
</pre>
 
 
=={{header|Forth}}==
 
{{works with|gforth|0.7.3}}
Inspired from Wikipedia. Use of a buffer.
May be also of interest : github.com/lietho/base64-forth
<syntaxhighlight lang="forth">variable bitsbuff
 
: alphabase ( u -- c ) $3F and C" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 1+ + c@ ;
: storecode ( u f -- ) if drop '=' else alphabase then c, ;
 
: 3bytesin ( addrf addr -- n )
$0 bitsbuff !
3 0 do
dup I + c@ bitsbuff @ 8 lshift + bitsbuff !
loop
-
;
 
: 4chars, ( n -- ) ( n=# of bytes )
4 0 do
dup I - 0<
bitsbuff @ 18 rshift swap storecode
bitsbuff @ 6 lshift bitsbuff !
loop drop
;
 
: b64enc ( addr1 n1 -- addr2 n2 )
here rot rot ( addr2 addr1 n1 )
over + dup rot ( addr2 addr1+n1 addr1+n1 addr1 )
do
dup I 3bytesin 4chars,
3 +loop drop ( addr2 )
dup here swap - ( addr2 n2 )
;
</syntaxhighlight>
 
{{out}}
<pre>s" favicon.ico" slurp-file b64enc cr type
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAA
(.../...)
AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE= ok
s" any carnal pleasure." b64enc cr type
YW55IGNhcm5hbCBwbGVhc3VyZS4= ok
s" any carnal pleasure" b64enc cr type
YW55IGNhcm5hbCBwbGVhc3VyZQ== ok
</pre>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim Shared As String B64
B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
"abcdefghijklmnopqrstuvwxyz" & _
"0123456789+/"
 
#define E0(v1) v1 Shr 2
#define E1(v1, v2) ((v1 And 3) Shl 4) + (v2 Shr 4)
#define E2(v2, v3) ((v2 And &H0F) Shl 2) + (v3 Shr 6)
#define E3(v3) (v3 And &H3F)
 
Function Encode64(S As String) As String
Dim As Integer j, k, l = Len(S)
Dim As String mE
If l = 0 Then Return mE
mE = String(((l+2)\3)*4,"=")
For j = 0 To l - ((l Mod 3)+1) Step 3
mE[k+0]=B64[e0(S[j+0])]
mE[k+1]=B64[e1(S[j+0],S[j+1])]
mE[k+2]=B64[e2(S[j+1],S[j+2])]
mE[k+3]=B64[e3(S[j+2])]:k+=4
Next j
If (l Mod 3) = 2 Then
mE[k+0]=B64[e0(S[j+0])]
mE[k+1]=B64[e1(S[j+0],S[j+1])]
mE[k+2]=B64[e2(S[j+1],S[j+2])]
mE[k+3]=61
Elseif (l Mod 3) = 1 Then
mE[k+0]=B64[e0(S[j+0])]
mE[k+1]=B64[e1(S[j+0],S[j+1])]
mE[k+2]=61
mE[k+3]=61
End If
Return mE
End Function
 
Dim As String msg64 = "To err is human, but to really foul things up you need a computer." & _
Chr(10) & " -- Paul R. Ehrlich"
Print msg64
Print: Print(Encode64(msg64))
Sleep</syntaxhighlight>
{{out}}
<pre>To err is human, but to really foul things up you need a computer.
-- Paul R. Ehrlich
 
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">b = readBytes["https://rosettacode.org/favicon.ico"]
println[base64Encode[b,undef,64]]</syntaxhighlight>
{{out}}
<pre>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xh
BQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAA
OpgAABdwnLpRPAAAAWJQTFRFAAAA/8IA/8EA/8IA/8IA/8IA/8IA/8IA/8IA/8IA
/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA
/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8UA/8UA/8QA/8IA/8IA/8IA/8IA/8IA
/8IA/8MAdWVhiHJUiHJUc2Rj/8MA/8IA/8IA/8IA/8IA/8IA06QfjXZQjnZQjXVR
3qwX/8IA/8IA/8IA/8IA/8IA/8kAjHVRjnZQjnZQjHVR/8gA/8IA/8IA/8IAjHVR
jHVR/8gA/8IA/8IA1aYejXZQjnZQjXVR3qwX/8IA/8IA/8IA/8MAdGRjh3FVcmNj
/8MA/8IA/8QA/8UA/8UA/8UA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA
/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IAjnZQ////pZF7sgAAAHN0Uk5T
AAAAA5iNAjzp5DUSMTAQYPz6WBEEjPCUG8G7GZrvhkfqRTV2MUvy50Jc9FoZRUQW
X/vzDau2Gab7nRi6qQwlWyZR9fJIKCMnYVBJK624GqX6nhm8C/VcGEEWYFczdXQv
SvGI7O0awBeXLA9f+VY+5jiZkk/hQmMAAAABYktHRHWoapj7AAAACXBIWXMAAA3X
AAAN1wFCKJt4AAAA7UlEQVQY0z1P11ICARDbFTvIKZ4HooiA7USxYMHGqRSxY6HY
AAULxRr+f1zAMU+ZzCabEAnY1A50dDL9oY27uoGeXm4qbLb0WZV+YMA2KIxJHdI0
u2MYcI6Maq4xE7nHAZfH6/NNTE4B0zOkz8q1f24+sLC4BCzbKLgCrK6th0Ibm1vA
9g5x2DB29/br9Ug0phtxJj5QErHDhnB0nFDCTMET4PTsPJm8uLwSyzXpKQlNZ7LZ
m9tG6B15pKTmvn/I5QuPzbfqU7Fkf34R3+tbqSjF2FouV6pSvfZeEcatcR9S9/OL
/+ey+g38tOb/AjOBNqW00PrwAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE1LTA4LTAy
VDIwOjM5OjEwKzAwOjAw98IZEQAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNS0wOC0w
MlQyMDozOToxMCswMDowMIafoa0AAABGdEVYdHNvZnR3YXJlAEltYWdlTWFnaWNr
IDYuNy44LTkgMjAxNC0wNS0xMiBRMTYgaHR0cDovL3d3dy5pbWFnZW1hZ2ljay5v
cmfchu0AAAAAGHRFWHRUaHVtYjo6RG9jdW1lbnQ6OlBhZ2VzADGn/7svAAAAGHRF
WHRUaHVtYjo6SW1hZ2U6OmhlaWdodAAxOTIPAHKFAAAAF3RFWHRUaHVtYjo6SW1h
Z2U6OldpZHRoADE5MtOsIQgAAAAZdEVYdFRodW1iOjpNaW1ldHlwZQBpbWFnZS9w
bmc/slZOAAAAF3RFWHRUaHVtYjo6TVRpbWUAMTQzODU0Nzk1MNul3mEAAAAPdEVY
dFRodW1iOjpTaXplADBCQpSiPuwAAABWdEVYdFRodW1iOjpVUkkAZmlsZTovLy9t
bnRsb2cvZmF2aWNvbnMvMjAxNS0wOC0wMi8xNDBkYmM4M2RmNWY3NmQyNmIzYWNl
M2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSlog.incl"
 
local fn EncodeStringAsBase64( stringToEncode as CFStringRef ) as CFStringRef
CFStringRef encodedBase64Str = NULL
CFDataRef dataToEncode = fn StringData( stringToEncode, NSUTF8StringEncoding )
encodedBase64Str = fn DataBase64EncodedString( dataToEncode, 0 )
end fn = encodedBase64Str
 
 
local fn DecodeBase64String( base64String as CFStringRef ) as CFStringRef
CFStringRef decodedString = NULL
CFDataRef encodedData = fn DataWithBase64EncodedString( base64String, NSDataBase64DecodingIgnoreUnknownCharacters )
decodedString = fn StringWithData( encodedData, NSUTF8StringEncoding )
end fn = decodedString
 
 
CFStringRef originalString, encodedBase64String, decodedBase64String
 
originalString = @"This is a test string to be encoded as Base64 and then decoded."
NSLog( @"This is the original string:\n\t%@\n", originalString )
 
encodedBase64String = fn EncodeStringAsBase64( originalString )
NSLog( @"This is the original string encoded as Base84:\n\t%@\n", encodedBase64String )
 
decodedBase64String = fn DecodeBase64String( encodedBase64String )
NSLog( @"This is the Base64 string decoded:\n\t%@", decodedBase64String )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
This is the original string:
This is a test string to be encoded as Base64 and then decoded.
 
This is the original string encoded as Base84:
VGhpcyBpcyBhIHRlc3Qgc3RyaW5nIHRvIGJlIGVuY29kZWQgYXMgQmFzZTY0IGFuZCB0aGVuIGRlY29kZWQu
 
This is the Base64 string decoded:
This is a test string to be encoded as Base64 and then decoded.
</pre>
 
 
 
=={{header|Go}}==
===Standard Library===
<langsyntaxhighlight Golang="go">package main
 
import (
Line 727 ⟶ 974:
}
fmt.Println(base64.StdEncoding.EncodeToString(d))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 733 ⟶ 980:
</pre>
===Manual implementation===
<langsyntaxhighlight lang="go">// base64 encoding
// A port, with slight variations, of the C version found here:
// http://rosettacode.org/wiki/Base64#C (manual implementation)
Line 833 ⟶ 1,080:
}
fmt.Printf("%s", encoded)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 847 ⟶ 1,094:
{{Trans|C}}
This Haskell code is ported from the C solution (manual implementation) with slight variations.
<langsyntaxhighlight Haskelllang="haskell">-- | Base 64 Encoding.
-- A port, with slight variations, of the C version found here:
-- http://rosettacode.org/wiki/Base64#C (manual implementation)
Line 912 ⟶ 1,159:
 
main :: IO ()
main = C.getContents >>= C.putStr . b64EncodePretty</langsyntaxhighlight>
 
===Using Data.ByteString.Base64===
<langsyntaxhighlight lang="haskell">import qualified Data.ByteString.Base64 as Base64 (decode, encode)
import qualified Data.ByteString.Char8 as B (putStrLn, readFile)
 
main :: IO ()
main = B.readFile "favicon.ico" >>= (B.putStrLn . Base64.encode)</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution''' (''[http://www.jsoftware.com/wsvn/addons/trunk/convert/misc/base64.ijs standard library]''):<langsyntaxhighlight lang="j"> load'convert/misc/base64' NB. use 'tobase64'</langsyntaxhighlight>
'''Solution''' (''handrolled''):<langsyntaxhighlight lang="j"> tobase64 =: padB64~ b2B64
padB64 =: , '=' #~ 0 2 1 i. 3 | #
b2B64 =: BASE64 {~ _6 #.\ (8#2) ,@:#: a.&i.</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="j"> load'web/gethttp'
76 {. tobase64 gethttp 'http://rosettacode.org/favicon.ico'
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA</langsyntaxhighlight>
 
=={{header|Java}}==
<p>
Java offers the <code>Base64</code> class, which includes both the <code>Encoder</code> and <code>Decoder</code> classes.<br />
The implementation supports RFC 4648 and RFC 2045.
</p>
<p>
The usage is very simple, supply a <code>byte</code> array, and it will return, either an encoded <code>byte</code> array, or
an ISO 8859-1 encoded <code>String</code>.
</p>
<p>
The class uses a static construct, so instead of instantiation via a constructor, you use one of the <kbd>static</kbd> methods.<br />
In this case we'll use the <code>Base64.getEncoder</code> method to acquire our instance.
</p>
<syntaxhighlight lang="java">
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
</syntaxhighlight>
<syntaxhighlight lang="java">
byte[] encodeFile(String path) throws IOException {
try (FileInputStream stream = new FileInputStream(path)) {
byte[] bytes = stream.readAllBytes();
return Base64.getEncoder().encode(bytes);
}
}
</syntaxhighlight>
<p>
The result appears to be slightly different than some other language implementations, so I imagine the image has changed.<br />
It's a total of 20,116 bytes, so here's a shortened output.
</p>
<pre>
AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
ADAAAABgAAAAAQAgAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
...
wv//AMH/hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPw/AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQh
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=
</pre>
 
<br />
Althernately<br />
Can also use org.apache.commons.codec.binary.Base64 from Apache Commons Codec
 
<langsyntaxhighlight Javalang="java">import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
Line 1,004 ⟶ 1,289:
}
}
}</langsyntaxhighlight>
<pre>AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=</pre>
 
=== Java 8 version ===
<lang java>import java.nio.file.*;
import java.util.Base64;
 
public class Base64Task {
 
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Paths.get("favicon.ico"));
String result = Base64.getEncoder().encodeToString(bytes);
System.out.println(result);
}
}</lang>
 
<pre>AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">(function(){//ECMAScript doesn't have an internal base64 function or method, so we have to do it ourselves, isn't that exciting?
function stringToArrayUnicode(str){for(var i=0,l=str.length,n=[];i<l;i++)n.push(str.charCodeAt(i));return n;}
function generateOnesByLength(n){//Attempts to generate a binary number full of ones given a length.. they don't redefine each other that much.
Line 1,087 ⟶ 1,357:
 
return toBase64(stringToArrayUnicode("Nothing seems hard to the people who don't know what they're talking about."))
}())</langsyntaxhighlight>
 
===Using btoa (HTML5)===
Line 1,095 ⟶ 1,365:
HTML5 saves the day! introducing two methods to the DOM!
These are btoa and atob, see [http://dev.w3.org/html5/spec-LC/webappapis.html#atob spec]
<langsyntaxhighlight JavaScriptlang="javascript">window.btoa("String to encode, etc..");//Will throw error if any unicode character is larger than 255 it's counterpart it's the window.atob</langsyntaxhighlight>To make it.. just work, you could convert it to UTF-8 Manually or..
JSON.stringify it or..
encodeURIComponent it.
Line 1,101 ⟶ 1,371:
===Using Node.js===
{{works with|Node.js}}
<langsyntaxhighlight JavaScriptlang="javascript">var http = require('http');
var options = {
host: 'rosettacode.org',
Line 1,115 ⟶ 1,385:
});
}
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
Line 1,121 ⟶ 1,391:
<nowiki>https://jsish.org/fossil/jsi/wiki/Wget</nowiki> and also listed at [[HTTP#Jsish]].
 
<langsyntaxhighlight lang="javascript">/* Base64, in Jsish */
require('httpGet');
var icon = httpGet('http://rosettacode.org/favicon.ico');
printf("%s", Util.base64(icon, false))</langsyntaxhighlight>
 
{{out}}
Line 1,130 ⟶ 1,400:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA
AAAAAQAAAAEAAAABAAAAAQAAAAE=prompt$</pre>
 
=={{header|jq}}==
{{works with|jq|gojq 0.12.4 (rev: 374bae6)}}
<pre>gojq -Rrs @base64 favicon.ico | egrep -o '^.{20}|.{20}$'
AAABAAIAEBAAAAAAAABo
AAEAAAABAAAAAQAAAAE=</pre>
To verify that gojq's `@base64 behaves properly:<pre>$ cmp <(base64 favicon.ico) <( gojq -Rrs @base64 favicon.ico)
$</pre>
 
To verify that the encode-decode round-trip is idempotent:
<pre>$ cmp favicon.ico <(gojq -Rrs @base64 favicon.ico|gojq -Rj @base64d)
$</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Requests
 
file = read(get("https://rosettacode.org/favicon.ico"))
encoded = base64encode(file)
 
print(encoded)</langsyntaxhighlight>
 
{{out}}
Line 1,145 ⟶ 1,427:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 1,155 ⟶ 1,437:
val base64 = Base64.getEncoder().encodeToString(bytes)
println(base64)
}</langsyntaxhighlight>
 
{{out}}
Line 1,163 ⟶ 1,445:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso ">local(
src = curl('http://rosettacode.org/favicon.ico'),
srcdata = #src->result
Line 1,170 ⟶ 1,452:
 
// or, in one movement:
curl('http://rosettacode.org/favicon.ico')->result->encodebase64</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put URL "http://rosettacode.org/favicon.ico" into rosettaico
put base64encode(rosettaico)
 
Ouput
AAABAA...S0tLS0tLS0t...QAAAAE=</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
local dic = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
function encode( t, f )
Line 1,212 ⟶ 1,494:
end
print()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,221 ⟶ 1,503:
AAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
</pre>
 
=={{header|M2000 Interpreter}}==
Using Urlmon.dll, UrlDownloadToFileW() function.
 
<syntaxhighlight lang="m2000 interpreter">
function global DownLoad$(filename$, drive$){
Const BINDF_GETNEWESTVERSION = 0x10&
if internet then
If exist(filename$) then Try {dos "del "+quote$(dir$+filename$);} : Wait 200
Declare URLDownloadToFile lib "urlmon.URLDownloadToFileW" {
long pCaller, szUrl$, sxFilename$, long dwReserved, long callback
}
if URLDownloadToFile(0,drive$, dir$+filename$,BINDF_GETNEWESTVERSION,0)==0 then
= "Ok"
Else
= "Try Again"
end if
else
= "No Internet, Try Again"
end if
}
iF Download$("rosettacode.ico","https://rosettacode.org/favicon.ico")="Ok" then
a=buffer("rosettacode.ico")
R$=string$(Eval$(a) as Encode64,0,0)
clipboard R$
report r$
end if
</syntaxhighlight>
{{out}}
<pre>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xh
BQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAA
.................
bnRsb2cvZmF2aWNvbnMvMjAxNS0wOC0wMi8xNDBkYmM4M2RmNWY3NmQyNmIzYWNl
M2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==
</pre>
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ExportString[Import["http://rosettacode.org/favicon.ico", "Text"], "Base64"]</syntaxhighlight>
<lang Mathematica>Print[ExportString[
Import["http://rosettacode.org/favicon.ico", "Text"], "Base64"]];</lang>
Very interesting results.
{{out}}
Line 1,234 ⟶ 1,553:
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import base64
import httpclient
 
var client = newHttpClient()
let content = client.getContent("http://rosettacode.org/favicon.ico")
let encoded = encode(content)
 
if encoded.len <= 64:
echo encoded
else:
echo encoded[0..31] & "..." & encoded[^32..^1]</syntaxhighlight>
 
{{out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|Objective-C}}==
{{works with|Mac OS X|10.6+}}
{{works with|iOS|4.0+}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(int argc, const char *argv[]) {
Line 1,246 ⟶ 1,581:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,277 ⟶ 1,612:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define base64-codes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(define kernel (alist->ff (map cons (iota (string-length base64-codes)) (string->bytes base64-codes))))
Line 1,326 ⟶ 1,661:
 
(encode "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.")
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,335 ⟶ 1,670:
 
The rosettacode icon:
<langsyntaxhighlight lang="scheme">
(define icon (runes->string (bytevector->list (file->bytevector "favicon.ico"))))
(encode icon)
</syntaxhighlight>
</lang>
<pre>
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCG
Line 1,346 ⟶ 1,681:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 1,353 ⟶ 1,688:
local $/;
print encode_base64(<$fh>);
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,361 ⟶ 1,696:
 
=={{header|Phix}}==
For simplicity, the example from wp:
As this is a draft task, I've gone with the example from wp, for now. [[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]]) 10:25, 11 September 2015 (UTC)
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins\base64.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">base64</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
string s = "Man is distinguished, not only by his reason, but by this singular passion from "&
"other animals, which is a lust of the mind, that by a perseverance of delight "&
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Man is distinguished, not only by his reason, but by this singular passion from "</span><span style="color: #0000FF;">&</span>
"in the continued and indefatigable generation of knowledge, exceeds the short "&
<span style="color: #008000;">"other animals, which is a lust of the mind, that by a perseverance of delight "</span><span style="color: #0000FF;">&</span>
"vehemence of any carnal pleasure."
<span style="color: #008000;">"in the continued and indefatigable generation of knowledge, exceeds the short "</span><span style="color: #0000FF;">&</span>
string e = encode_base64(s)
<span style="color: #008000;">"vehemence of any carnal pleasure."</span>
?e
<span style="color: #004080;">string</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">encode_base64</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
?decode_base64(e)</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">e</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">decode_base64</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,378 ⟶ 1,716:
"Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight i
n the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."
</pre>
This downloads, encodes, decodes, and verifies the icon:
{{libheader|Phix/libcurl}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">url</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"https://rosettacode.org/favicon.ico"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">out</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_file_name</span><span style="color: #0000FF;">(</span><span style="color: #000000;">url</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"\nattempting to download remote file %s to local file %s\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">url</span><span style="color: #0000FF;">,</span><span style="color: #000000;">out</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">CURLcode</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_get_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">url</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">out</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (no proxy)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">!=</span><span style="color: #004600;">CURLE_OK</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Error %d downloading file\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"file %s saved\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">out</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">raw</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">out</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_WHOLE_FILE</span><span style="color: #0000FF;">+</span><span style="color: #000000;">GT_BINARY</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">b64</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">encode_base64</span><span style="color: #0000FF;">(</span><span style="color: #000000;">raw</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">chk</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">decode_base64</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b64</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"base 64: %s, same: %t\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b64</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"chars"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">chk</span><span style="color: #0000FF;">==</span><span style="color: #000000;">raw</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
attempting to download remote file https://rosettacode.org/favicon.ico to local file favicon.ico
 
file favicon.ico saved
base 64: AAABAAIAEBAAAAAAAABo...AAEAAAABAAAAAQAAAAE= (4,852 chars), same: true
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php echo base64_encode(file_get_contents("http://rosettacode.org/favicon.ico"));/*1 liner*/ ?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">`(== 64 64)
(setq *Char64
`'(chop
Line 1,428 ⟶ 1,796:
(test
"c3VyZS4="
(base64 "sure.") )</langsyntaxhighlight>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
string icon = Protocols.HTTP.get_url_data("http://rosettacode.org/favicon.ico");
// The default base64 encodeing linefeeds every 76 chars
Line 1,437 ⟶ 1,805:
// For brivety, just print the first and last line
write("%s\n...\n%s\n", encoded_lines[0], encoded_lines[-1]);
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,446 ⟶ 1,814:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">$webClient = [Net.WebClient]::new()
$bytes = $webClient.DownloadData('http://rosettacode.org/favicon.ico')
$output = [Convert]::ToBase64String($bytes)
$output</langsyntaxhighlight>
{{out}}
<pre>
Line 1,458 ⟶ 1,826:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">InitNetwork()
*BufferRaw = ReceiveHTTPMemory("http://rosettacode.org/favicon.ico")
Line 1,465 ⟶ 1,833:
Else
Debug "Download failed"
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
===Python 2===
<lang python>import urllib
<syntaxhighlight lang="python">import urllib
import base64
 
data = urllib.urlopen('http://rosettacode.org/favicon.ico').read()
print base64.b64encode(data)</langsyntaxhighlight>
(For me this gets the wrong data; the data is actually an error message. But still, it base-64 encodes it.)
 
===Python 3===
<syntaxhighlight lang="python">import base64 # for b64encode()
from urllib.request import urlopen
 
print(base64.b64encode(urlopen('http://rosettacode.org/favicon.ico').read()))
# Open the URL, retrieve the data and encode the data.</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require net/url net/base64)
(base64-encode (call/input-url (string->url "http://rosettacode.org/favicon.ico")
get-pure-port port->bytes))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
#"AAABAAIAEBAAAAAAAABoBQAA...AQAAAAE=\r\n"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub MAIN {
my $buf = slurp("./favicon.ico", :bin);
say buf-to-Base64($buf);
Line 1,511 ⟶ 1,887:
else { take '==' }
}
}</langsyntaxhighlight>
{{out}}
<pre>AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAA...QAAAAEAAAABAAAAAQAAAAE=</pre>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">Red [Source: https://github.com/vazub/rosetta-red]
 
print enbase read/binary https://rosettacode.org/favicon.ico
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,530 ⟶ 1,906:
 
A much higher value for &nbsp; '''chunk''' &nbsp; could be used for modern systems or implementations.
<langsyntaxhighlight lang="rexx">/*REXX program converts text (from a file or the C.L.) to a base64 text string. */
parse arg iFID @ /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID='favicon.ico' /*Not specified? Then use the default.*/
Line 1,559 ⟶ 1,935:
end /*j*/
/* [↓] maybe append equal signs to $. */
return $ || copies('=', 2 * (L//6==2) + (L//6==4) )</langsyntaxhighlight>
For the various outputs, several input texts from the Wikipedia article on &nbsp; ''Base64'' &nbsp; [http://en.wikipedia.org/wiki/Base64] &nbsp; were used to demonstrate how padding works.
<br><br>
Line 1,596 ⟶ 1,972:
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhcw==
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
#=======================================#
# Description : Base64 Sample
# Author : Mansour Ayouni
#=======================================#
 
# Loading RingQt
 
load "guilib.ring"
# Creating a QByteArray object
 
oQByteArray = new QByteArray()
 
# Adding a string to the QByteArray object
oQByteArray.append("my string")
 
# Encoding the content of the QByteArray in a base64 string
? oQByteArray.toBase64().data()
 
# To do the inverse operation:
# You put your base64 string inside a QByteArray object
 
oQByteArray = new QByteArray()
oQByteArray.append("bXkgc3RyaW5n")
? oQByteArray.fromBase64(oQByteArray).data()
</syntaxhighlight>
{{out}}
<pre>
bXkgc3RyaW5n
my string
</pre>
 
=={{header|RPL}}==
{{works with|RPL|HP-49C}}
« 3 OVER SIZE 3 MOD DUP 3 IFTE -
SWAP ""
1 PICK3 SIZE '''FOR''' j
OVER j DUP SUB NUM
256 + R→B →STR 4 OVER SIZE 1 - SUB +
'''NEXT'''
NIP "0000" 1 4 PICK 2 * SUB +
» '<span style="color:blue">STR→BITS</span>' STO <span style="color:grey">''@ ( "string" → fill "bits" )''</span>
« BIN 8 STWS <span style="color:blue">STR→BITS</span>
""
1 PICK3 SIZE '''FOR''' j
OVER j DUP 5 + SUB "b" + "#" SWAP + STR→ B→R
{ 25 51 61 62 63 } OVER ≥ 1 POS
{ 65 71 -4 -19 -16 } SWAP GET + CHR +
6 '''STEP'''
NIP "==" 1 4 ROLL SUB +
» '<span style="color:blue">→B64</span>' STO
 
"Hello, RPL!" <span style="color:blue">→B64</span>
"To err is human, but to really foul things up you need a computer.\n -- Paul R. Ehrlich" <span style="color:blue">→B64</span>
{{out}}
<pre>
2: "SGVsbG8sIFJQTCEA=="
1:"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'open-uri'
require 'base64'
 
puts Base64.encode64 open('http://rosettacode.org/favicon.ico') {|f| f.read}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.net.URL
import java.util.Base64
 
Line 1,618 ⟶ 2,058:
 
println(s"Successfully completed without errors. [total ${compat.Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,625 ⟶ 2,065:
which encodes a string with the Base64 encoding.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "gethttp.s7i";
include "encoding.s7i";
Line 1,632 ⟶ 2,072:
begin
writeln(toBase64(getHttp("rosettacode.org/favicon.ico")));
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
put "To err is human, but to really foul things up you need a computer. --Paul R.Ehrlich" as base64
put url "http://rosettacode.org/favicon.ico" as base64
put base64Encode ("To err is human, but to really foul things up you need a computer. --Paul R.Ehrlich")
</lang>
</syntaxhighlight>
Output:
<langsyntaxhighlight lang="sensetalk">
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVk
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA
IGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=
AAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm
5ACgo6EAV1pYABcZGADO0c8AODs5AK2wrgBzdnQA6+7sAPz//QAAAwEAAAAAAAAAAAAAAAAA
...
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVk
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA
IGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=
/////wAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAA
</syntaxhighlight>
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAE=
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var data = %f'favicon.ico'.read(:raw) # binary string
print data.encode_base64 # print to STDOUT</langsyntaxhighlight>
 
=={{header|Slope}}==
<syntaxhighlight lang="slope">
(define table-reg "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
(define table-alt "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=")
 
; The second argument to encode, if given, will be treated as a bool
; a truthy value will have the encoding be URL safe
(define encode (lambda (in ...)
(if (not (pair? in))
(set! in (string->bytes (append "" in))))
(define table (if (and (pair? ...) (car ...)) table-alt table-reg))
(define b-length (length in))
(define pad-length
(if (equal? (% b-length 3) 1)
2
(if (equal? (% b-length 3) 2)
1
0)))
(define size (+ b-length pad-length))
(define src-arr in)
(define dst-arr in)
(cond
((equal? pad-length 1) (set! dst-arr (append dst-arr 0)))
((equal? pad-length 2) (set! dst-arr (append dst-arr 0 0))))
(define result [])
(for ((i 0 (+ i 3))) ((< i size))
(define a (ref dst-arr i))
(define b (ref dst-arr (+ i 1)))
(define c (ref dst-arr (+ i 2)))
(define is-last (> (+ i 3) b-length))
(set! result
(append result
(>> a 2)
(| (<< (& a 3) 4) (>> b 4))))
(if (or (not is-last) (zero? pad-length))
(set! result
(append result
(| (<< (& b 15) 2) (>> c 6))
(& c 63)))
(if (equal? pad-length 2)
(set! result (append result "=" "="))
(if (equal? pad-length 1)
(set! result (append result (| (<< (& b 15) 2) (>> c 6)) "="))))))
(list->string
(map
(lambda (code)
(if (string? code)
"="
(ref table code)))
result))))
 
(load-mod request) ; available from slp
(define data (request::fetch "http://rosettacode.org/favicon.ico"))
(display (encode data))
</syntaxhighlight>
 
'''Output''':
<syntaxhighlight lang="slope">
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAWJQTFRFAAAA/8IA/8EA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8UA/8UA/8QA/8IA/8IA/8IA/8IA/8IA/8IA/8MAdWVhiHJUiHJUc2Rj/8MA/8IA/8IA/8IA/8IA/8IA06QfjXZQjnZQjXVR3qwX/8IA/8IA/8IA/8IA/8IA/8kAjHVRjnZQjnZQjHVR/8gA/8IA/8IA/8IAjHVRjHVR/8gA/8IA/8IA1aYejXZQjnZQjXVR3qwX/8IA/8IA/8IA/8MAdGRjh3FVcmNj/8MA/8IA/8QA/8UA/8UA/8UA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IA/8IAjnZQ////pZF7sgAAAHN0Uk5TAAAAA5iNAjzp5DUSMTAQYPz6WBEEjPCUG8G7GZrvhkfqRTV2MUvy50Jc9FoZRUQWX/vzDau2Gab7nRi6qQwlWyZR9fJIKCMnYVBJK624GqX6nhm8C/VcGEEWYFczdXQvSvGI7O0awBeXLA9f+VY+5jiZkk/hQmMAAAABYktHRHWoapj7AAAACXBIWXMAAA3XAAAN1wFCKJt4AAAA7UlEQVQY0z1P11ICARDbFTvIKZ4HooiA7USxYMHGqRSxY6HYAAULxRr+f1zAMU+ZzCabEAnY1A50dDL9oY27uoGeXm4qbLb0WZV+YMA2KIxJHdI0u2MYcI6Maq4xE7nHAZfH6/NNTE4B0zOkz8q1f24+sLC4BCzbKLgCrK6th0Ibm1vA9g5x2DB29/br9Ug0phtxJj5QErHDhnB0nFDCTMET4PTsPJm8uLwSyzXpKQlNZ7LZm9tG6B15pKTmvn/I5QuPzbfqU7Fkf34R3+tbqSjF2FouV6pSvfZeEcatcR9S9/OL/+ey+g38tOb/AjOBNqW00PrwAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE1LTA4LTAyVDIwOjM5OjEwKzAwOjAw98IZEQAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNS0wOC0wMlQyMDozOToxMCswMDowMIafoa0AAABGdEVYdHNvZnR3YXJlAEltYWdlTWFnaWNrIDYuNy44LTkgMjAxNC0wNS0xMiBRMTYgaHR0cDovL3d3dy5pbWFnZW1hZ2ljay5vcmfchu0AAAAAGHRFWHRUaHVtYjo6RG9jdW1lbnQ6OlBhZ2VzADGn/7svAAAAGHRFWHRUaHVtYjo6SW1hZ2U6OmhlaWdodAAxOTIPAHKFAAAAF3RFWHRUaHVtYjo6SW1hZ2U6OldpZHRoADE5MtOsIQgAAAAZdEVYdFRodW1iOjpNaW1ldHlwZQBpbWFnZS9wbmc/slZOAAAAF3RFWHRUaHVtYjo6TVRpbWUAMTQzODU0Nzk1MNul3mEAAAAPdEVYdFRodW1iOjpTaXplADBCQpSiPuwAAABWdEVYdFRodW1iOjpVUkkAZmlsZTovLy9tbnRsb2cvZmF2aWNvbnMvMjAxNS0wOC0wMi8xNDBkYmM4M2RmNWY3NmQyNmIzYWNlM2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==
</syntaxhighlight>
 
=={{header|Standard ML}}==
Using smlnj-lib:
<syntaxhighlight lang="sml">
fun b64enc filename =
let
val instream = BinIO.openIn filename
val data = BinIO.inputAll instream
in
Base64.encode data before BinIO.closeIn instream
end
</syntaxhighlight>
 
{{out}}
<pre>
- b64enc "/tmp/favicon.ico";
val it =
"AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNg#"
: string
</pre>
Note the "#" means the output is truncated.
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require http
 
Line 1,663 ⟶ 2,183:
http::cleanup $tok
 
puts [binary encode base64 -maxlen 64 $icondata]</langsyntaxhighlight>
With older versions of Tcl, the base64 encoding is best supported via an external package:
{{tcllib|base64}}
<langsyntaxhighlight lang="tcl">package require base64
package require http
 
Line 1,673 ⟶ 2,193:
http::cleanup $tok
 
puts [base64::encode -maxlen 64 $icondata]</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
Public Function Decode(s As String) As String
Dim i As Integer, j As Integer, r As Byte
Line 1,784 ⟶ 2,304:
Debug.Print "Result of string comparison of input and decoded output: " & StrComp(In_, bIn, vbBinaryCompare)
Debug.Print "A zero indicates both strings are equal."
End Sub</langsyntaxhighlight>
{{out}}<pre>The first eighty and last eighty characters after encoding:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB
Line 1,791 ⟶ 2,311:
Result of string comparison of input and decoded output: 0.
A zero indicates both strings are equal.</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import net.http
import encoding.base64
import os
 
fn main() {
resp := http.get("http://rosettacode.org/favicon.ico") or {println(err) exit(-1)}
encoded := base64.encode_str(resp.body)
println(encoded)
// Check if can decode and save
decoded := base64.decode_str(encoded)
os.write_file("./favicon.ico", decoded) or {println("File not created or written to!")}
}
</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-seq}}
From first principles using string manipulation. Quick enough here.
<syntaxhighlight lang="wren">import "io" for File, Stdout
import "./fmt" for Conv, Fmt
import "./seq" for Lst
 
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 
var encode = Fn.new { |s|
var c = s.count
if (c == 0) return s
var e = ""
for (b in s) e = e + Fmt.swrite("$08b", b)
if (c == 2) {
e = e + "00"
} else if (c == 1) {
e = e + "0000"
}
var i = 0
while (i < e.count) {
var ix = Conv.atoi(e[i..i+5], 2)
System.write(alpha[ix])
i = i + 6
}
if (c == 2) {
System.write("=")
} else if (c == 1) {
System.write("==")
}
Stdout.flush()
}
 
var s = File.read("favicon.ico").bytes.toList
for (chunk in Lst.chunks(s, 3)) encode.call(chunk)
System.print()</syntaxhighlight>
 
{{out}}
<pre>
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZ
....
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
</pre>
 
=={{header|XPL0}}==
The end of the input file is detected here by detecting the error when
attempting to read beyond the end. The first attempt to read beyond the
end returns an EOF code ($1A -- useful when reading text files). The
second attempt to read beyond the end causes an error, which by default
aborts a program. However, error trapping is turned off here [with
Trap(false)] and GetErr is used to detect the error, and thus the
end-of-file.
 
The output here is different than other examples because the icon at the
provided link has changed.
<syntaxhighlight lang "XPL0">int Char;
func GetCh; \Return character from input file (with one-char look-ahead)
int Prev;
[Prev:= Char;
Char:= ChIn(3);
return Prev;
];
 
char Base64;
int FD, Acc, Bytes, Column;
[Base64:= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ";
Trap(false); \disable error trapping; use GetErr instead
 
FD:= FOpen("favicon.ico", 0); \open input file
FSet(FD, ^I);
OpenI(3);
 
FD:= FOpen("favicon.txt", 1); \open file for output
FSet(FD, ^O);
OpenO(3);
 
Char:= ChIn(3); \initialize one-char look-ahead
Column:= 0;
loop [Acc:= 0; Bytes:= 0;
Acc:= GetCh<<16;
if GetErr then quit;
Bytes:= Bytes+1;
Acc:= Acc + GetCh<<8;
if GetErr = 0 then
[Bytes:= Bytes+1;
Acc:= Acc + GetCh;
if GetErr = 0 then Bytes:= Bytes+1;
];
ChOut(3, Base64(Acc>>18));
ChOut(3, Base64(Acc>>12 & $3F));
ChOut(3, if Bytes < 2 then ^= else Base64(Acc>>6 & $3F));
ChOut(3, if Bytes < 3 then ^= else Base64(Acc & $3F));
Column:= Column+4;
if Column >= 76 then [Column:= 0; CrLf(3)];
if Bytes < 3 then quit;
];
if Column # 0 then CrLf(3);
Close(3);
]</syntaxhighlight>
{{out}}
<pre>
AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
...
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=
</pre>
 
=={{header|zkl}}==
Using shared libraries for cURL and message hashing:
<langsyntaxhighlight lang="zkl">var [const] MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl");
icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0)
Line 1,802 ⟶ 2,445:
icon==MsgHash.base64decode(b64));
b64.println();
b64.text.println();</langsyntaxhighlight>
{{out}}
Encoded to 72 characters per line
1,150

edits