Jump to content

Base64 encode data

From Rosetta Code
(Redirected from Base64)
Base64 encode data is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Convert an array of bytes or binary string to the base64-encoding of that string and output that value. Use the icon for Rosetta Code as the data to convert.

See also Base64 decode data.

ABAP

DATA: li_client  TYPE REF TO if_http_client,
      lv_encoded TYPE string,
      lv_data    TYPE xstring.


cl_http_client=>create_by_url(
  EXPORTING
    url    = 'http://rosettacode.org/favicon.ico'
  IMPORTING
    client = li_client ).

li_client->send( ).
li_client->receive( ).

lv_data = li_client->response->get_data( ).

CALL FUNCTION 'SSFC_BASE64_ENCODE'
  EXPORTING
    bindata = lv_data
  IMPORTING
    b64data = lv_encoded.

WHILE strlen( lv_encoded ) > 100.
  WRITE: / lv_encoded(100).
  lv_encoded = lv_encoded+100.
ENDWHILE.
WRITE: / lv_encoded.
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAA
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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
Output:

Screenshot from Atari 8-bit computer

AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
...
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Ada

Library: AWS
with Ada.Text_IO;

with AWS.Response;
with AWS.Client;
with AWS.Translator;

procedure Encode_AWS is
   URL     : constant String := "http://rosettacode.org/favicon.ico";
   Page    : constant AWS.Response.Data := AWS.Client.Get (URL);
   Payload : constant String := AWS.Response.Message_Body (Page);
   Icon_64 : constant String := AWS.Translator.Base64_Encode (Payload);
begin
   Ada.Text_IO.Put_Line (Icon_64);
end Encode_AWS;
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAA
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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.

STRING codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[@0];

PROC get web page = (STRING host, path) STRING:
   BEGIN
      STRING reply;
      INT rc;
      IF rc := tcp request (reply, host,
                               "GET /favicon.ico  HTTP/1.0" + crlf +
                               "Host: rosettacode.org" + crlf +
                               crlf, 80);
            rc = 0 THEN
	 SKIP #print (reply)#
      ELSE print (strerror (rc))
      FI;
      IF rc = 0 AND grep in string ("^HTTP/[0-9.]+ 200", reply, NIL, NIL) = 0 THEN
	 INT p := 0;
	 FOR i TO UPB reply WHILE p = 0 DO
	    IF reply[i] = carriage return ANDF reply[i+1] = line feed AND reply[i+2] = carriage return AND reply[i+3] = line feed THEN
	       p := i
	    FI
	 OD;	       
	 IF p /= 0 THEN
	    STRING headers = reply[:p],
	           body = reply[p+4:];
	    body
	 ELSE
	    ""
	 FI 
      ELSE 
	 print (strerror (rc)); ""
      FI
   END;


PROC base64_encode = (STRING s) STRING:
   BEGIN 
      STRING result := "";
      BITS u;
      FOR i BY 3 TO UPB s DO
	 u := BIN ABS s[i] SHL 16 OR
	      IF i+1 <= UPB s THEN BIN ABS s[i+1] SHL 8 OR
	         IF i+2 <= UPB s THEN BIN ABS s[i+2]
		 ELSE 16r0
                 FI 
	      ELSE 16r0
	      FI;

	 result +:= codes[ABS (u SHR 18 AND 16r3f)] +
                    codes[ABS (u SHR 12 AND 16r3f)] + 
	            (i + 1 <= UPB s | codes[ABS (u SHR 6 AND 16r3f)] | "=") +
		    (i + 2 <= UPB s | codes[ABS (u AND 16r3f)] | "=")
      OD;
      result
   END;


CHAR line feed = REPR 10, carriage return = REPR 13;
STRING crlf = carriage return + line feed;
STRING host = "rosettacode.org";

STRING rosettacode icon = get web page (host, "http://rosettacode.org/favicon.ico");
STRING encoded icon = base64_encode (rosettacode icon);
print ((encoded icon, new line))
Output:
First 80 chars and last 80 chars of output
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB
...
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

ARM Assembly

.section .rodata
ch64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
example_text: .ascii "Hello World"
example_base64: .ascii "SGVsbG8gV29ybGQ="

.section .bss
.lcomm buffer, 64

.section .text
.global _start

@ int base64_encode(char *d, char *s, int len)
base64_encode:
    push {r3-r7}
    ldr r6, =ch64
    mov r7, r0
be_cycle:
    ldrb r3, [r1]
    lsr r4, r3, #2
    ldrb r4, [r6, r4]
    strb r4, [r0]

    add r0, r0, #1
    add r1, r1, #1
    subs r2, r2, #1
    moveq r4, #0
    ldrneb r4, [r1]

    and r3, r3, #3
    lsl r3, r3, #4
    lsr r5, r4, #4
    orr r3, r3, r5
    ldrb r3, [r6, r3]
    strb r3, [r0]

    add r0, r0, #1
    add r1, r1, #1
    beq be_store2
    subs r2, r2, #1
    moveq r3, #0
    ldrneb r3, [r1]

    and r4, r4, #15
    lsl r4, r4, #2
    lsr r5, r3, #6
    orr r4, r4, r5
    ldrb r4, [r6, r4]
    strb r4, [r0]

    add r0, r0, #1
    add r1, r1, #1
    beq be_store1

    and r3, r3, #0x3f
    ldrb r3, [r6, r3]
    strb r3, [r0]

    add r0, r0, #1
    subs r2, r2, #1
    beq be_exit
    bne be_cycle
be_store2:
    mov r3, #'='
    strb r3, [r0]
    add r0, r0, #1
be_store1:
    mov r3, #'='
    strb r3, [r0]
    add r0, r0, #1
be_exit:
    sub r0, r0, r7
    pop {r3-r7}
    mov pc, lr

@ int base64_decode(char *d, char *s, int len)
base64_decode:
    push {r3-r6,lr}
    mov r3, r0
    mov r6, r0
bd_cycle:
    ldrb r0, [r1]
    bl char_decode
    add r1, r1, #1

    lsl r4, r0, #2
    ldrb r0, [r1]
    bl char_decode
    add r1, r1, #1

    lsr r5, r0, #4
    orr r4, r4, r5
    strb r4, [r3]
    add r3, r3, #1

    lsl r4, r0, #4
    ldrb r0, [r1]
    cmp r0, #'='
    beq exit
    bl char_decode
    add r1, r1, #1

    lsr r5, r0, #2
    orr r4, r4, r5
    strb r4, [r3]
    add r3, r3, #1

    lsl r4, r0, #6
    ldrb r0, [r1]
    cmp r0, #'='
    beq exit
    bl char_decode
    add r1, r1, #1

    orr r4, r4, r0
    strb r4, [r3]
    add r3, r3, #1
    subs r2, r2, #4
    bne bd_cycle
exit:
    sub r0, r3, r6
    pop {r3-r6, pc}

@ char char_decode(char c)
char_decode:
    subs r0, r0, #'A'
    blt cd_digit
    cmp r0, #25
    subgt r0, r0, #6
    mov pc, lr
cd_digit:
    adds r0, r0, #17
    blt cd_ps
    add r0, r0, #52
    mov pc, lr
cd_ps:
    cmn r0, #5
    moveq r0, #62
    movne r0, #63
    mov pc, lr

_start:
    ldr r0, =buffer
    ldr r1, =example_text
    mov r2, #11
    bl base64_encode
    
    mov r2, r0
    mov r7, #4
    mov r0, #1
    ldr r1, =buffer
    swi #0
    
    ldr r0, =buffer
    ldr r1, =example_base64
    mov r2, #16
    bl base64_decode

    mov r2, r0
    mov r7, #4
    mov r0, #1
    ldr r1, =buffer
    swi #0

    mov r7, #1
    mov r0, #0
    swi #0

BASIC

BaCon

CONST file$ = "favicon.ico"
binary = BLOAD(file$)
PRINT B64ENC$(binary, FILELEN(file$))
FREE binary
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAE.......QAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

C

libresolv

Library: libresolv

(libresolv is included on most Unix-like systems)

#include <stdio.h>
#include <stdlib.h>
#include <resolv.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main() {
  int fin = open("favicon.ico",  O_RDONLY);
  if (fin == -1)
    return 1;

  struct stat st;
  if (fstat(fin, &st))
    return 1;

  void *bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin,  0);
  if (bi == MAP_FAILED)
    return 1;

  int outLength = ((st.st_size + 2) / 3) * 4 + 1;
  char *outBuffer = malloc(outLength);
  if (outBuffer == NULL)
    return 1;

  int encodedLength = b64_ntop(bi, st.st_size, outBuffer, outLength);
  if (encodedLength < 0)
    return 1;

  puts(outBuffer);

  free(outBuffer);
  munmap(bi, st.st_size);
  close(fin);

  return 0;
}

Compile with

gcc -lresolv -o base64encode base64encode.c

Manual implementation

The following reads standard input and writes base64-encoded stream to standard output, e.g. ./a.out <some_random_file >/dev/null if you don't want to see the output. It gives identical output as the common base64 utility program, though much less efficiently.

#include <stdio.h>
#include <unistd.h>

typedef unsigned long UL;

int main(void)
{
	const char *alpha =	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
				"abcdefghijklmnopqrstuvwxyz"
				"0123456789+/";
	unsigned char c[4];
	UL u, len, w = 0;

	do {
		c[1] = c[2] = 0;

		if (!(len = read(fileno(stdin), c, 3))) break;
		u = (UL)c[0]<<16 | (UL)c[1]<<8 | (UL)c[2];

		putchar(alpha[u>>18]);
		putchar(alpha[u>>12 & 63]);
		putchar(len < 2 ? '=' : alpha[u>>6 & 63]);
		putchar(len < 3 ? '=' : alpha[u & 63]);

		if (++w == 19) w = 0, putchar('\n');
	} while (len == 3);

	if (w) putchar('\n');

	return 0;
}

C#

namespace RosettaCode.Base64EncodeData
{
    using System;
    using System.Net;

    internal static class Program
    {
        private static void Main()
        {
            const string path = "http://rosettacode.org/favicon.ico";

            byte[] input;
            using (var client = new WebClient())
            {
                input = client.DownloadData(path);
            }

            var output = Convert.ToBase64String(input);
            Console.WriteLine(output);
        }
    }
}

Output:

AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

C++

#include <iostream>
#include <fstream>
#include <vector>

typedef unsigned char byte;
using namespace std;

const unsigned m1 = 63 << 18, m2 = 63 << 12, m3 = 63 << 6;

class base64
{
public:
    base64() { char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; }
    string encode( vector<byte> v )
    {
	string res;
	unsigned d, a = 0, l = static_cast<unsigned>( v.size() );
	while( l > 2 )
	{
	    d = v[a++] << 16 | v[a++] << 8 | v[a++];	
	    res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );	
	    res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );	
	    res.append( 1, char_set.at( ( d & m3 ) >>  6 ) );
	    res.append( 1, char_set.at( d & 63 ) );
	    l -= 3;
	}
	if( l == 2 )
	{
	    d = v[a++] << 16 | v[a++] << 8;
	    res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );	
	    res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );	
	    res.append( 1, char_set.at( ( d & m3 ) >>  6 ) );
	    res.append( 1, '=' );
	}
	else if( l == 1 )
	{
	    d = v[a++] << 16;
	    res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );	
	    res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );	
	    res.append( "==", 2 );
	}
	return res;
    }

private:
    string char_set;
};

int main( int argc, char* argv[] )
{
    base64 b;
    basic_ifstream<byte> f( "favicon.ico", ios::binary );
    string r = b.encode( vector<byte>( ( istreambuf_iterator<byte>( f ) ), istreambuf_iterator<byte>() ) );
    copy( r.begin(), r.end(), ostream_iterator<char>( cout ) );
    return 0;
}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZ
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAA
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Commodore BASIC

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.

100 print chr$(247);chr$(14);
110 dim a$(63): rem alphabet
120 dim i(2): rem input bytes
130 dim o$(3): rem output characters
140 for i=0 to 25
150 : a$(i) = chr$(asc("A")+i)
160 : a$(26+i) = chr$(asc("a")+i)
170 : if i < 10 then a$(52+i) = chr$(asc("0")+i)
180 next i
190 a$(62) = "+"
200 a$(63) = "/"
210 p$="=":rem padding char
220 input "source file";s$
230 open 1,8,2,s$+",p": if st then 450
240 input "dest file";d$
250 open 2,8,3,d$+",s,w": if st then 450
260 for d=0 to 1 step 0: rem while not d(one)
270 : p=0:for o=0 to 3:o$(o)=p$:next o
280 : for i=0 to 2
290 :   i(i)=0
300 :   if d then 330
310 :   get#1,i$: if len(i$) then i(i)=asc(i$)
320 :   if st and 64 then p=2-i:d=1
330 : next i
340 : o$(0) = a$( (i(0) and 252) / 4 )
350 : o$(1) = a$( (i(0) and 3) * 16  + (i(1) and 240) / 16 )
360 : if p<2 then o$(2) = a$( (i(1) and 15) * 4 + (i(2) and 192) / 64 )
370 : if p<1 then o$(3) = a$( i(2) and 63 )
380 : for o=0 to 3: print o$(o);:print#2, o$(o);:next o
390 : c=c+4:if c >= 76 then c=0:print:print#2,chr$(13);
400 next d
410 print:print#2,chr$(13);
420 close 1
430 close 2
440 end
450 print "error:"st
460 open 15,8,15:input#15,ds,ds$,a,b:close15
470 print ds,ds$,a,b
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EA
...
AOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA/////wAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Common Lisp

A nice example for the CL eco system using cl-base64 and drakma.

(eval-when (:load-toplevel :compile-toplevel :execute)
  (ql:quickload "drakma")
  (ql:quickload "cl-base64"))

;; * The package definition
(defpackage :base64-encode
  (:use :common-lisp :drakma :cl-base64))
(in-package :base64-encode)

;; * The function
(defun base64-encode (&optional (uri "https://rosettacode.org/favicon.ico"))
  "Returns the BASE64 encoded string of the file at URI."
    (let* ((input (http-request uri :want-stream t))
        (output (loop
                   with array = (make-array 0 :element-type 'unsigned-byte
                                              :adjustable t :fill-pointer 0)
                   for data-chunk = (read-byte input nil nil)
                   while data-chunk
                   do (vector-push-extend data-chunk array)
                   finally (return (usb8-array-to-base64-string array)))))
   (close input)
   output))
Output:
"AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///...

Crystal

require "http/client"
require "base64"

response = HTTP::Client.get "https://rosettacode.org/favicon.ico"
if response.success?
    Base64.encode(response.body, STDOUT)
end


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;
}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAwqgIAADCjgUAACgAAAAQAAAAIAA...
AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQ==

Delphi

program Base64EncodeData;
{$APPTYPE CONSOLE}
uses IdHTTP, IdCoderMIME;

var
  lSrcString: string;
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lSrcString := lHTTP.Get('http://rosettacode.org/favicon.ico');
    Writeln(TIdEncoderMIME.EncodeString(lSrcString));
  finally
    lHTTP.Free;
  end;
end.

DuckDB

Works with: DuckDB version V1.0
duckdb -noheader -list <<< $'select to_base64(content) from read_blob(\'favicon.ico\');' |
  egrep -o '^.{20}|.{20}$'
AAABAAIAEBAAAAAAAABo
AAEAAAABAAAAAQAAAAE=

To check that DuckDB from_base64() agrees with the system's base64:

$ cmp <(base64 favicon.ico) <( duckdb -noheader -list <<< $'
   select to_base64(content) from read_blob(\'favicon.ico\');')
$

To verify that the encode-decode round-trip is idempotent:

$ duckdb <<< $'
  with favicon as (select content from read_blob(\'favicon.ico\'))
  select from_base64(to_base64(content)) = content from favicon;'

┌─────────────────────────────────────────────────┐
│ (from_base64(to_base64("content")) = "content") │
│                     boolean                     │
├─────────────────────────────────────────────────┤
│ true                                            │
└─────────────────────────────────────────────────┘

Ed

See the sister algo Base64_decode_data#Ed for implementation details/quirks.

H
,p
g/(.)/s// \1 /g
# text -> binary
g/[ ]![ ]/s//00100001/g
g/[ ]"[ ]/s//00100010/g
g/[ ]#[ ]/s//00100011/g
g/[ ]$[ ]/s//00100100/g
g/[ ]%[ ]/s//00100101/g
g/[ ]\&[ ]/s//00100110/g
g/[ ]'[ ]/s//00100111/g
g/[ ]\([ ]/s//00101000/g
g/[ ]\)[ ]/s//00101001/g
g/[ ]\*[ ]/s//00101010/g
g/[ ]\+[ ]/s//00101011/g
g/[ ],[ ]/s//00101100/g
g/[ ]-[ ]/s//00101101/g
g/[ ]\.[ ]/s//00101110/g
g/[ ]/[ ]/s//00101111/g
g/[ ]0[ ]/s//00110000/g
g/[ ]1[ ]/s//00110001/g
g/[ ]2[ ]/s//00110010/g
g/[ ]3[ ]/s//00110011/g
g/[ ]4[ ]/s//00110100/g
g/[ ]5[ ]/s//00110101/g
g/[ ]6[ ]/s//00110110/g
g/[ ]7[ ]/s//00110111/g
g/[ ]8[ ]/s//00111000/g
g/[ ]9[ ]/s//00111001/g
g/[ ]:[ ]/s//00111010/g
g/[ ];[ ]/s//00111011/g
g/[ ]<[ ]/s//00111100/g
g/[ ]=[ ]/s//00111101/g
g/[ ]>[ ]/s//00111110/g
g/[ ]\?[ ]/s//00111111/g
g/[ ]@[ ]/s//01000000/g
g/[ ]A[ ]/s//01000001/g
g/[ ]B[ ]/s//01000010/g
g/[ ]C[ ]/s//01000011/g
g/[ ]D[ ]/s//01000100/g
g/[ ]E[ ]/s//01000101/g
g/[ ]F[ ]/s//01000110/g
g/[ ]G[ ]/s//01000111/g
g/[ ]H[ ]/s//01001000/g
g/[ ]I[ ]/s//01001001/g
g/[ ]J[ ]/s//01001010/g
g/[ ]K[ ]/s//01001011/g
g/[ ]L[ ]/s//01001100/g
g/[ ]M[ ]/s//01001101/g
g/[ ]N[ ]/s//01001110/g
g/[ ]O[ ]/s//01001111/g
g/[ ]P[ ]/s//01010000/g
g/[ ]Q[ ]/s//01010001/g
g/[ ]R[ ]/s//01010010/g
g/[ ]S[ ]/s//01010011/g
g/[ ]T[ ]/s//01010100/g
g/[ ]U[ ]/s//01010101/g
g/[ ]V[ ]/s//01010110/g
g/[ ]W[ ]/s//01010111/g
g/[ ]X[ ]/s//01011000/g
g/[ ]Y[ ]/s//01011001/g
g/[ ]Z[ ]/s//01011010/g
g/[ ]\[[ ]/s//01011011/g
g/[ ]\\[ ]/s//01011100/g
g/[ ]\][ ]/s//01011101/g
g/[ ]\^[ ]/s//01011110/g
g/[ ]_[ ]/s//01011111/g
g/[ ]`[ ]/s//01100000/g
g/[ ]a[ ]/s//01100001/g
g/[ ]b[ ]/s//01100010/g
g/[ ]c[ ]/s//01100011/g
g/[ ]d[ ]/s//01100100/g
g/[ ]e[ ]/s//01100101/g
g/[ ]f[ ]/s//01100110/g
g/[ ]g[ ]/s//01100111/g
g/[ ]h[ ]/s//01101000/g
g/[ ]i[ ]/s//01101001/g
g/[ ]j[ ]/s//01101010/g
g/[ ]k[ ]/s//01101011/g
g/[ ]l[ ]/s//01101100/g
g/[ ]m[ ]/s//01101101/g
g/[ ]n[ ]/s//01101110/g
g/[ ]o[ ]/s//01101111/g
g/[ ]p[ ]/s//01110000/g
g/[ ]q[ ]/s//01110001/g
g/[ ]r[ ]/s//01110010/g
g/[ ]s[ ]/s//01110011/g
g/[ ]t[ ]/s//01110100/g
g/[ ]u[ ]/s//01110101/g
g/[ ]v[ ]/s//01110110/g
g/[ ]w[ ]/s//01110111/g
g/[ ]x[ ]/s//01111000/g
g/[ ]y[ ]/s//01111001/g
g/[ ]z[ ]/s//01111010/g
g/[ ]\{[ ]/s//01111011/g
g/[ ]\|[ ]/s//01111100/g
g/[ ]\}[ ]/s//01111101/g
g/[ ]~[ ]/s//01111110/g
# Two special cases last so that they don't interfere with the rest of whitespace-separated conversion
g/[ ][ ][ ]/s//00100000/g
g/$/s//00001010/g
,j
# split into blocks of six
g/[01]{6}/s// & /g
g/\b[01]{1}\b/s//&0/g
g/\b[01]{2}\b/s//&0/g
g/\b[01]{3}\b/s//&0/g
g/\b[01]{4}\b/s//&0/g
g/\b[01]{5}\b/s//&0/g
# And encode the combinations to base64
g/000000/s//A/g
g/000001/s//B/g
g/000010/s//C/g
g/000011/s//D/g
g/000100/s//E/g
g/000101/s//F/g
g/000110/s//G/g
g/000111/s//H/g
g/001000/s//I/g
g/001001/s//J/g
g/001010/s//K/g
g/001011/s//L/g
g/001100/s//M/g
g/001101/s//N/g
g/001110/s//O/g
g/001111/s//P/g
g/010000/s//Q/g
g/010001/s//R/g
g/010010/s//S/g
g/010011/s//T/g
g/010100/s//U/g
g/010101/s//V/g
g/010110/s//W/g
g/010111/s//X/g
g/011000/s//Y/g
g/011001/s//Z/g
g/011010/s//a/g
g/011011/s//b/g
g/011100/s//c/g
g/011101/s//d/g
g/011110/s//e/g
g/011111/s//f/g
g/100000/s//g/g
g/100001/s//h/g
g/100010/s//i/g
g/100011/s//j/g
g/100100/s//k/g
g/100101/s//l/g
g/100110/s//m/g
g/100111/s//n/g
g/101000/s//o/g
g/101001/s//p/g
g/101010/s//q/g
g/101011/s//r/g
g/101100/s//s/g
g/101101/s//t/g
g/101110/s//u/g
g/101111/s//v/g
g/110000/s//w/g
g/110001/s//x/g
g/110010/s//y/g
g/110011/s//z/g
g/110100/s//0/g
g/110101/s//1/g
g/110110/s//2/g
g/110111/s//3/g
g/111000/s//4/g
g/111001/s//5/g
g/111010/s//6/g
g/111011/s//7/g
g/111100/s//8/g
g/111101/s//9/g
g/111110/s//+/g
g/111111/s//\//g
g/[[:space:]]/s///g
,p
Q
Output:
$ cat base64-encode.ed | ed -E base64-encode.input 
Newline appended
108
I am sending you my book,
O my reader, today;
It's up to you to read
Or throw it away.
-- Yeghishe Charents
?
Unknown command
SSBhbSBzZW5kaW5nIHlvdSBteSBib29rLApPIG15IHJlYWRlciwgdG9kYXk7Ckl0J3MgdXAgdG8geW91IHRvIHJlYWQKT3IgdGhyb3cgaXQgYXdheS4KLS0gWWVnaGlzaGUgQ2hhcmVudHMK
?
Warning: buffer modified

Elixir

data = File.read!("favicon.ico")
encoded = :base64.encode(data)
IO.puts encoded
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Erlang

-module(base64demo).
-export([main/0]).

main() ->
    {ok, Data} = file:read_file("favicon.ico"),
    Encoded = encode_library(Data),
    io:format("~s",[Encoded]).

%% Demonstrating with the library function.
encode_library(Data) ->
    base64:encode(Data).
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4F...AAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

F#

Standard Library

Works with: fsharp version 4.5
open System
open System.Net

let url = "https://rosettacode.org/favicon.ico"

let download (url: string) =
    use client = new WebClient()
    client.DownloadData url

let raw = download url
let encoded = Convert.ToBase64String raw

printfn "%s" encoded
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAA ...

Manual Implementation

Works with: fsharp version 4.5
open System.Net

let encode s =
    let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".ToCharArray()
                |> Array.map string
    let paddingSize =
        let c = Array.length s % 3
        if c = 0 then 0 else 3 - c
    let s = Array.append s (Array.replicate paddingSize (byte '\x00')) |> Array.map int
    let calc c =
        let n = (s.[c] <<< 16) + (s.[c + 1] <<< 8) + s.[c + 2]
        let n1 = (n >>> 18) &&& 63
        let n2 = (n >>> 12) &&& 63
        let n3 = (n >>> 6) &&& 63
        let n4 = n &&& 63
        chars.[n1] + chars.[n2] + chars.[n3] + chars.[n4]
    [0..3..Array.length s - 1]
    |> List.map calc
    |> List.reduce (+)
    |> fun r -> r.Substring(0, String.length r - paddingSize) + String.replicate paddingSize "="
 
let url = "https://rosettacode.org/favicon.ico"
 
let download (url: string) =
    use client = new WebClient()
    client.DownloadData url

let encoded = url |> download |> encode

printfn "%s" encoded
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAA ...

Factor

USING: base64 http.client io kernel strings ;

"http://rosettacode.org/favicon.ico" http-get nip
>base64-lines >string print
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=


Forth

Works with: gforth version 0.7.3

Inspired from Wikipedia. Use of a buffer. May be also of interest : github.com/lietho/base64-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 )
;
Output:
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

Fortran

A self-contained program that takes a filename on the command line as an argument. That file is subsequently encoded using RFC-4648 rules and displayed on stdout.

program demo_base64
! base64-encode data to RFC-4648 and print to standard output
! usage: base64 inputfile > outputfile
use,intrinsic :: iso_fortran_env, only: stderr=>ERROR_UNIT, stdout=>OUTPUT_UNIT
use,intrinsic :: iso_fortran_env, only : int32
implicit none
integer(kind=int32)          :: i, j, column, sz, pad, iostat
character(len=1),allocatable :: text(:)
character(len=:),allocatable :: infile 
character(len=4)             :: chunk
integer,parameter            :: rfc4648_linelength=76
character(len=1),parameter   :: rfc4648_padding='='
   infile=get_arg(1)
   ! allocate array and copy file into it and pad with two characters at end
   call slurp(infile,text) 
   ! figure out how many characters at end are pad characters
   sz=size(text)-2
   pad=3-mod(sz,3)
   column=0
   ! place three bytes and zero into 32bit integer
   ! take sets of 6 bits from integer and place into every 8 bits
   do i=1,sz,3
      chunk=three2four(text(i:i+2))
      if(i.gt.sz-3)then ! if at end put any pad characters in place
         if(pad.gt.0.and.pad.lt.3)then
            chunk(5-pad:)=repeat(rfc4648_padding,pad)
         endif
      endif
      if(column.ge.rfc4648_linelength)then
         write(stdout,'(a)')
         flush(unit=stdout,iostat=iostat)
         column=0
      endif
      write(stdout,'(a)',advance='no')chunk
      column=column+4
   enddo
   if(column.ne.0)write(stdout,'(a)')
contains

function three2four(tri) result(quad)
character(len=1),intent(in) :: tri(3)
character(len=4)            :: quad
integer(kind=int32)         :: i32, i, j, k, iout(4)
character(len=*),parameter  :: rfc4648_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
   i32 = transfer([(tri(j),j=3,1,-1),achar(0)], i32 )
   iout = 0
   ! The bits are numbered 0 to BIT_SIZE(I)-1, from right to left.
   do j=0,3
      call  mvbits(i32, (j)*6, 6, iout(4-j), 0)
      k=4-j
      quad(k:k)=rfc4648_alphabet(iout(k)+1:iout(k)+1)
   enddo
end function three2four

function get_arg(iarg) result(value)
! get nth argument from command line
integer,intent(in)           :: iarg
character(len=:),allocatable :: value
integer                      :: argument_length, istat
   call get_command_argument(number=iarg,length=argument_length)
   if(allocated(value))deallocate(value)
   allocate(character(len=argument_length) :: value)
   value(:)=''
   call get_command_argument(iarg, value, status=istat)
end function get_arg

subroutine slurp(filename,text)
! allocate text array and read file filename into it, padding on two characters
character(len=*),intent(in)              :: filename 
character(len=1),allocatable,intent(out) :: text(:)   
integer            :: nchars=0, igetunit, iostat=0, i
character(len=256) :: iomsg
character(len=1)   :: byte
   open(newunit=igetunit, file=trim(filename), action="read", iomsg=iomsg,&
   &form="unformatted", access="stream",status='old',iostat=iostat)
   if(iostat /= 0) stop '<ERROR> *slurp* '//trim(iomsg)
   inquire(unit=igetunit, size=nchars)
   if(nchars <= 0)then
      write(stderr,'(a)')'*slurp* empty file '//trim(filename)
      return
   endif
   allocate( text(nchars+2) )             ! storage holds file and two padding characters
   read(igetunit,iostat=iostat,iomsg=iomsg) text(:nchars) ! load input file -> text array
   if(iostat /= 0) stop '*slurp* bad read of '//trim(filename)//':'//trim(iomsg)
   text(size(text)-1:)=repeat(achar(0),2) ! init padding characters
   close(iostat=iostat,unit=igetunit)     ! close if opened successfully or not
end subroutine slurp

end program demo_base64
Output:

The first and last line of the program output using the favicon.ico file for the Rosetta Code icon file:

AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
...
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=


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
Output:
To err is human, but to really foul things up you need a computer.
    -- Paul R. Ehrlich

VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=

Frink

b = readBytes["https://rosettacode.org/favicon.ico"]
println[base64Encode[b,undef,64]]
Output:
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==


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
Output:
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.


Go

Standard Library

package main

import (
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    r, err := http.Get("http://rosettacode.org/favicon.ico")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer r.Body.Close()
    d, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(base64.StdEncoding.EncodeToString(d))
}
Output:
AAABAAIAEBAAAAAAAABoBQAAJg ... AAAABAAAAAQAAAAE=

Manual implementation

// base64 encoding
// A port, with slight variations, of the C version found here:
// http://rosettacode.org/wiki/Base64#C (manual implementation)
//
// go build ; cat favicon.ico | ./base64

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

const (
	B64_CHUNK_SIZE = 76
)

type UL int64

// Our lookup table.
var alpha string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

// Base64 encode a raw byte stream.
func B64Encode(raw []byte) (string, error) {
	var buffer strings.Builder
	var reader *bytes.Reader
	var u UL // w UL
	var length int
	var chunk []byte
	var err error

	length = 3
	reader = bytes.NewReader(raw)
	chunk = make([]byte, 3)

	for length == 3 {

		chunk[1] = 0
		chunk[2] = 0

		length, err = reader.Read(chunk)
		if err != nil || len(chunk) == 0 {
			break
		}

		u = UL(chunk[0])<<16 | UL(chunk[1])<<8 | UL(chunk[2])

		buffer.WriteString(string(alpha[u>>18]))
		buffer.WriteString(string(alpha[u>>12&63]))
		if length < 2 {
			buffer.WriteString("=")
		} else {
			buffer.WriteString(string(alpha[u>>6&63]))
		}

		if length < 3 {
			buffer.WriteString("=")
		} else {
			buffer.WriteString(string(alpha[u&63]))
		}
	}

	return buffer.String(), nil
}

// Prettifies the base64 result by interspersing \n chars every B64_CHUNK_SIZE bytes.
// Even though there's a performance hit, i'd rather compose these.
func B64EncodePretty(raw []byte) (string, error) {
	var buffer strings.Builder
	encoded, err := B64Encode(raw)
	if err != nil {
		return "", err
	}
	length := len(encoded)
	chunks := int(length/B64_CHUNK_SIZE) + 1
	for i := 0; i < chunks; i++ {
		chunk := i * B64_CHUNK_SIZE
		end := chunk + B64_CHUNK_SIZE
		if end > length {
			end = chunk + (length - chunk)
		}
		buffer.WriteString(encoded[chunk:end] + "\n")
	}
	return buffer.String(), err
}

func main() {
	contents, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatal("Error reading input: ", err)
	}
	encoded, err := B64EncodePretty(contents)
	if err != nil {
		log.Fatal("Error base64 encoding the input: ", err)
	}
	fmt.Printf("%s", encoded)
}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EA
...
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Haskell

By hand

Translation of: C

This Haskell code is ported from the C solution (manual implementation) with slight variations.

-- | Base 64 Encoding.
-- A port, with slight variations, of the C version found here:
-- http://rosettacode.org/wiki/Base64#C (manual implementation)
--
-- ghc -Wall base64_encode.hs ; cat favicon.ico | ./base64_encode
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}

module Main where

import Data.Bits
import Data.Char

import qualified Data.ByteString.Char8 as C

-- | alphaTable: Our base64 lookup table.
alphaTable :: C.ByteString
alphaTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

-- | b64Encode: Simple base64 encode function operating on normal C.ByteString's
b64Encode :: C.ByteString -> C.ByteString
b64Encode stream =
  if C.null stream
    then C.empty
    else alphaTable `C.index` shiftR _u 18 `C.cons` alphaTable `C.index`
         (shiftR _u 12 .&. 63) `C.cons`
         (if C.length chunk < 2
            then '='
            else alphaTable `C.index` (shiftR _u 6 .&. 63)) `C.cons`
         (if C.length chunk < 3
            then '='
            else alphaTable `C.index` (_u .&. 63)) `C.cons`
         b64Encode (C.drop 3 stream)
  where
    chunk = C.take 3 stream
    _u = u chunk

-- | b64EncodePretty: Intersperses \n every 76 bytes for prettier output
b64EncodePretty :: C.ByteString -> C.ByteString
b64EncodePretty = makePretty 76 . b64Encode

-- | u: base64 encoding magic
u :: C.ByteString -> Int
u chunk = fromIntegral result :: Int
  where
    result =
      foldl (.|.) 0 $
      zipWith
        shiftL
        (C.foldr (\c acc -> charToInteger c : acc) [] chunk)
        [16, 8, 0]

-- lazy foldl to fix formatting
-- | charToInteger: Convert a Char to an Integer
charToInteger :: Char -> Integer
charToInteger c = fromIntegral (ord c) :: Integer

-- | makePretty: Add new line characters throughout a character stream
makePretty :: Int -> C.ByteString -> C.ByteString
makePretty _ (C.uncons -> Nothing) = C.empty
makePretty by stream = first `C.append` "\n" `C.append` makePretty by rest
  where
    (first, rest) = C.splitAt by stream

main :: IO ()
main = C.getContents >>= C.putStr . b64EncodePretty

Using Data.ByteString.Base64

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)

J

Solution (standard library):

   load'convert/misc/base64'  NB. use 'tobase64'

Solution (handrolled):

   tobase64 =:  padB64~ b2B64 
     padB64 =:  , '=' #~ 0 2 1 i. 3 | #
     b2B64  =:  BASE64 {~ _6 #.\ (8#2) ,@:#: a.&i.

Example:

   load'web/gethttp'
   76 {. tobase64 gethttp 'http://rosettacode.org/favicon.ico'
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA

Java

Java offers the Base64 class, which includes both the Encoder and Decoder classes.
The implementation supports RFC 4648 and RFC 2045.

The usage is very simple, supply a byte array, and it will return, either an encoded byte array, or an ISO 8859-1 encoded String.

The class uses a static construct, so instead of instantiation via a constructor, you use one of the static methods.
In this case we'll use the Base64.getEncoder method to acquire our instance.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
byte[] encodeFile(String path) throws IOException {
    try (FileInputStream stream = new FileInputStream(path)) {
        byte[] bytes = stream.readAllBytes();
        return Base64.getEncoder().encode(bytes);
    }
}

The result appears to be slightly different than some other language implementations, so I imagine the image has changed.
It's a total of 20,116 bytes, so here's a shortened output.

AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
ADAAAABgAAAAAQAgAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
...
wv//AMH/hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPw/AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQh
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=


Althernately
Can also use org.apache.commons.codec.binary.Base64 from Apache Commons Codec

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

public class Base64 {

    private static final char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    static String base64(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        int blocks = 0;

        while (true) {
            int c0 = is.read();
            if (c0 == -1)
                break;
            int c1 = is.read();
            int c2 = is.read();

            int block = ((c0 & 0xFF) << 16) | ((Math.max(c1, 0) & 0xFF) << 8) | (Math.max(c2, 0) & 0xFF);

            sb.append(alpha[block >> 18 & 63]);
            sb.append(alpha[block >> 12 & 63]);
            sb.append(c1 == -1 ? '=' : alpha[block >> 6 & 63]);
            sb.append(c2 == -1 ? '=' : alpha[block & 63]);

            if (++blocks == 19) {
                blocks = 0;
                sb.append('\n');
            }
        }

        if (blocks > 0)
            sb.append('\n');

        return sb.toString();
    }

    private static void assertBase64(String expected, byte[] bytes) throws IOException {
        String actual = base64(new ByteArrayInputStream(bytes));
        if (!actual.equals(expected)) {
            throw new IllegalStateException(String.format("Expected %s for %s, but got %s.",
                    expected, Arrays.toString(bytes), actual));
        }
    }

    private static void testBase64() throws IOException {
        assertBase64("", new byte[]{});
        assertBase64("AA==\n", new byte[]{0});
        assertBase64("AAA=\n", new byte[]{0, 0});
        assertBase64("AAAA\n", new byte[]{0, 0, 0});
        assertBase64("AAAAAA==\n", new byte[]{0, 0, 0, 0});
        assertBase64("/w==\n", new byte[]{-1});
        assertBase64("//8=\n", new byte[]{-1, -1});
        assertBase64("////\n", new byte[]{-1, -1, -1});
        assertBase64("/////w==\n", new byte[]{-1, -1, -1, -1});
    }

    public static void main(String[] args) throws IOException {
        testBase64();

        URLConnection conn = new URL("http://rosettacode.org/favicon.ico").openConnection();
        conn.addRequestProperty("User-Agent", "Mozilla"); // To prevent an HTTP 403 error.
        try (InputStream is = conn.getInputStream()) {
            System.out.println(base64(is));
        }
    }
}
AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=

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.
        var x=0;
        for(var i=0;i<n;i++){
            x<<=1;x|=1;//I don't know if this is performant faster than Math.pow but seriously I don't think I'll need Math.pow, do I?
        }
        return x;
    }
    function paf(_offset,_offsetlength,_number){//I don't have any name for this function at ALL, but I will explain what it does, it takes an offset, a number and returns the base64 number and the offset of the next number.
        //the next function will be used to extract the offset of the number..
        var a=6-_offsetlength,b=8-a;//Oh god, 8 is HARDCODED! Because 8 is the number of bits in a byte!!!
        //And 6 is the mini-byte used by wikipedia base64 article... at least on 2013.
        //I imagine this code being read in 2432 or something, that probably won't happen..
        return [_number&generateOnesByLength(b),b,(_offset<<a)|(_number>>b)];//offset & offsetlength & number 
    }
    function toBase64(uint8array){//of bits, each value may not have more than 255 bits... //a normal "array" should work fine too..
        //From 0x29 to 0x5a plus from 0x61 to 0x7A AND from 0x30 to 0x39
        //Will not report errors if an array index has a value bigger than 255.. it will likely fail.
        var a=[],i,output=[];
        for(i=0x41;i<=0x5a;i++){//A-Z
            a.push(String.fromCharCode(i));
        }
        for(i=0x61;i<=0x7A;i++){//a-z
            a.push(String.fromCharCode(i));
        }
        for(i=0x30;i<=0x39;i++){//0-9
            a.push(String.fromCharCode(i));
        }
        a.push('+','/');
        var offset=0,offsetLength=0,x;
        for(var i=0,l=uint8array.length;i<l;i++){
            if(offsetLength==6){//if offsetlength is 6 that means that a whole offset is occupying the space of a byte, can you believe it.
                offsetLength=0;
                output.push(a[offset]);
                offset=0;
                i--;
                continue;
            }
            x=paf(offset,offsetLength,uint8array[i]);
            offset=x[0];
            offsetLength=x[1];
            output.push(a[x[2]]);
        }
        if(offsetLength){
            if(offsetLength==6){
                output.push(a[offset]);
            }else{
                var y=(6-offsetLength)/2;
                x=paf(offset,offsetLength,0);
                offset=x[0];
                output.push(a[x[2]]);
                switch (y){
                    case 2:output.push('=');//This thingy right here, you know.. the offsets also, no break statement;
                    case 1:output.push('=');break;
                }
            }
        }
        return output.join('');//You can change it so the result is an array instead!!!!
    }

    //Usage

    return toBase64(stringToArrayUnicode("Nothing seems hard to the people who don't know what they're talking about."))
}())

Using btoa (HTML5)

Works with: Gecko
Works with: WebKit

Works with IE10 or higher.
HTML5 saves the day! introducing two methods to the DOM! These are btoa and atob, see spec

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

To make it.. just work, you could convert it to UTF-8 Manually or..

JSON.stringify it or.. encodeURIComponent it.

Using Node.js

Works with: Node.js
var http = require('http');
var options = {
  host: 'rosettacode.org',
  path: '/favicon.ico'
};
callback = function(response) {
  var str = '';
  response.on('data', function (chunk) {
    str += chunk;
  });
  response.on('end', function () {
    console.log(new Buffer(str).toString('base64'));//Base64 encoding right here.
  });
}

Jsish

Using a contributed entry that is a small change of the Jsi lib/Jsi_Wget.jsi sources, to the httpGet.jsi module. Stored as an attachment at https://jsish.org/fossil/jsi/wiki/Wget and also listed at HTTP#Jsish.

/* Base64, in Jsish */
require('httpGet');
var icon = httpGet('http://rosettacode.org/favicon.ico');
printf("%s", Util.base64(icon, false))
Output:
prompt$ jsish base64.jsi | sed -ne '1p;$p'
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA
AAAAAQAAAAEAAAABAAAAAQAAAAE=prompt$

jq

Works with: jq version gojq 0.12.4 (rev: 374bae6)
gojq -Rrs @base64 favicon.ico | egrep -o '^.{20}|.{20}$'
AAABAAIAEBAAAAAAAABo
AAEAAAABAAAAAQAAAAE=

To verify that gojq's `@base64 behaves properly:

$ cmp <(base64 favicon.ico) <( gojq -Rrs @base64 favicon.ico)
$

To verify that the encode-decode round-trip is idempotent:

$ cmp favicon.ico <(gojq -Rrs @base64 favicon.ico|gojq -Rj @base64d) 
$

Julia

Works with: Julia version 0.6
using Requests

file = read(get("https://rosettacode.org/favicon.ico"))
encoded = base64encode(file)

print(encoded)
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP[...]QAAAAE=

Kotlin

// version 1.1.2

import java.io.File
import java.util.Base64

fun main(args: Array<String>) {
    val path = "favicon.ico" // already downloaded to current directory
    val bytes = File(path).readBytes()
    val base64 = Base64.getEncoder().encodeToString(bytes)
    println(base64)
}
Output:
AAABAAIAEBAAAAAAAABoBQ.....AAAAEAAAABAAAAAQAAAAE=

Lasso

local(
	src = curl('http://rosettacode.org/favicon.ico'),
	srcdata = #src->result
)
#srcdata->encodebase64

// or, in one movement:
curl('http://rosettacode.org/favicon.ico')->result->encodebase64

LiveCode

put URL "http://rosettacode.org/favicon.ico" into rosettaico
put base64encode(rosettaico)

Ouput
AAABAA...S0tLS0tLS0t...QAAAAE=

Lua

local dic = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
function encode( t, f ) 
    local b1, b2, b3, b4	
    b1 = 1 + ( ( t & 0xfc0000 ) >> 18 )
    b2 = 1 + ( ( t & 0x03f000 ) >> 12 )
    b3 = 1 + ( ( t & 0x000fc0 ) >>  6 )
    b4 = 1 + ( t & 0x00003f )
    io.write( dic:sub( b1, b1 ), dic:sub( b2, b2 ) )
    if f > 1 then io.write( dic:sub( b3, b3 ) ) else io.write( "=" ) end
    if f > 2 then io.write( dic:sub( b4, b4 ) ) else io.write( "=" ) end
end

local i = assert( io.open( "favicon.ico", "rb" ) )
local iconData = i:read( "*all" )
local dataLen, s, t = #iconData, 1
while( dataLen > 2 ) do 
    t =     ( iconData:sub( s, s ):byte() << 16 ); s = s + 1
    t = t + ( iconData:sub( s, s ):byte() <<  8 ); s = s + 1
    t = t + ( iconData:sub( s, s ):byte()       ); s = s + 1
    dataLen = dataLen - 3
    encode( t, 3 )
end 
if dataLen == 2 then
    t =	    ( iconData:sub( s, s ):byte() << 16 ); s = s + 1;
    t = t + ( iconData:sub( s, s ):byte() <<  8 ); s = s + 1;
    encode( t, 2 )
elseif dataLen == 1 then
    t =	    ( iconData:sub( s, s ):byte() << 16 ); s = s + 1;
    encode( t, 1 )
end
print()
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAA
gAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1r
...
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQ
AAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

M2000 Interpreter

Using Urlmon.dll, UrlDownloadToFileW() function.

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
Output:
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xh
BQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAA
.................
bnRsb2cvZmF2aWNvbnMvMjAxNS0wOC0wMi8xNDBkYmM4M2RmNWY3NmQyNmIzYWNl
M2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==


Mathematica / Wolfram Language

ExportString[Import["http://rosettacode.org/favicon.ico", "Text"], "Base64"]

Very interesting results.

Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EA
V1pYABcZGADO0c8AODs5AK2wrgBzdnQA6+7sAPz//QAAAwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
............................................................................
AOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA/////wAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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]
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Nu

http get -r 'https://rosettacode.org/favicon.ico' | encode base64
| str replace -r '^(.{38}).*(.{37})$' '$1 ... $2'
Output:
AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABAC ... hAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=

Objective-C

Works with: Mac OS X version 10.6+
Works with: iOS version 4.0+
#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {
  @autoreleasepool {
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://rosettacode.org/favicon.ico"]];
    NSLog(@"%@", [data base64Encoding]);
  }
  return 0;
}

OCaml

# First we install with opam the lib: https://github.com/mirage/ocaml-base64
$ opam install base64
# Be sure to use the opam environment
$ eval $(opam env)
# Download the file to encode (there is no simple KISS way to do it in OCaml)
$ wget http://rosettacode.org/favicon.ico
# Starting the ocaml toplevel
$ rlwrap ocaml -I $(ocamlfind query base64) base64.cma
        OCaml version 4.07.1

# let load_file f =
    let ic = open_in f in
    let n = in_channel_length ic in
    let s = Bytes.create n in
    really_input ic s 0 n;
    close_in ic;          
    (Bytes.to_string s)
  ;;
val load_file : string -> string = <fun>

# let enc = Base64.encode_exn (load_file "favicon.ico") ;;
val enc : string =
  "AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4F"... (* string length 4852; truncated *)

Ol

(define base64-codes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(define kernel (alist->ff (map cons (iota (string-length base64-codes)) (string->bytes base64-codes))))

; returns n bits from input binary stream
(define (bits n hold)
   (let loop ((hold hold))
      (vector-apply hold (lambda (v i l)
         (cond
            ; usual case
            ((pair? l)
               (if (not (less? i n))
                  (values (>> v (- i n)) (vector (band v (- (<< 1 (- i n)) 1)) (- i n) l))
                  (loop (vector
                     (bor (<< v 8) (car l))
                     (+ i 8)
                     (cdr l)))))
            ; special case - no more characters in input stream
            ((null? l)
               (cond
                  ((= i 0)
                     (values #false #false)) ; done
                  ((< i n)
                     (values (<< v (- n i)) (vector 0 0 #null)))
                  (else
                     (values (>> v (- i n)) (vector (band v (- (<< 1 (- i n)) 1)) (- i n) #null)))))
            ; just stream processing
            (else
               (loop (vector v i (force l)))))))))

; decoder.
(define (encode str)
   (case (mod
            (let loop ((hold [0 0 (str-iter str)]) (n 0))
               (let*((bit hold (bits 6 hold)))
                  (when bit (display (string (kernel bit))))
                  (if (not hold)
                     n
                     (loop hold (+ n 1)))))
            4)
      (2 (print "=="))
      (3 (print "="))
      (else (print))))

(encode "Hello, Lisp!")

(encode "To err is human, but to really foul things up you need a computer.\n    -- Paul R. Ehrlich")

(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.")
Output:
SGVsbG8sIExpc3Ah
MDEyMzQ=
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

The rosettacode icon:

(define icon (runes->string (bytevector->list (file->bytevector "favicon.ico"))))
(encode icon)
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCG
...
AABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Perl

#!perl
use strict;
use warnings;
use MIME::Base64;
open(my($fh), "<", "favicon.ico") or die;
local $/;
print encode_base64(<$fh>);
Output:

The first and last lines of output are:

AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Phix

For simplicity, the example from wp:

with javascript_semantics
include builtins\base64.e
 
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 "&
           "in the continued and indefatigable generation of knowledge, exceeds the short "&
           "vehemence of any carnal pleasure."
string e = encode_base64(s)
?e
?decode_base64(e)
Output:
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
"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."

This downloads, encodes, decodes, and verifies the icon:

Library: Phix/libcurl
without js
constant url = "https://rosettacode.org/favicon.ico",
         out = get_file_name(url)
    
printf(1, "\nattempting to download remote file %s to local file %s\n\n", {url,out})

include libcurl.e

CURLcode res = curl_easy_get_file(url,"",out) -- (no proxy)
if res!=CURLE_OK then
    printf(1, "Error %d downloading file\n", res)
else
    string raw = get_text(out,GT_WHOLE_FILE+GT_BINARY)
    printf(1, "file %s saved (%,d bytes)\n", {out,length(raw)})
    string b64 = encode_base64(raw),
           chk = decode_base64(b64)
    printf(1,"base 64: %s, same: %t\n",{shorten(b64,"chars"),chk==raw})
end if
Output:
attempting to download remote file https://rosettacode.org/favicon.ico to local file favicon.ico

file favicon.ico saved (15,086 bytes)
base 64: AAABAAMAMDAAAAEAIACo...AAD8PwAA/D8AAPw/AAA= (20,116 chars), same: true

(Aside: the icon seems to have increased from ~3K to ~15K since this was first written, output now matches Nu and XPL0 but no longer anything else)

PHP

<?php echo base64_encode(file_get_contents("http://rosettacode.org/favicon.ico"));/*1 liner*/  ?>

PicoLisp

`(== 64 64)
(setq *Char64
   `'(chop
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ) )
(de char64 (A B)
   (default B 0)
   (get *Char64 (inc (| A B))) )
(de base64 (S)
   (let S (mapcar char (chop S))
      (pack
         (make
            (while (cut 3 'S)
               (let ((A B C) @)
                  (link (char64 (>> 2 A)))
                  (nond
                     (B
                        (link
                           (char64 (>> -4 (& A 3)))
                           '=
                           '= ) )
                     (C
                        (link
                           (char64 (>> -4 (& A 3)) (>> 4 B))
                           (char64 (>> -2 (& B 15)))
                           '= ) )
                     (NIL
                        (link
                           (char64 (>> -4 (& A 3)) (>> 4 B))
                           (char64 (>> -2 (& B 15)) (>> 6 C))
                           (char64 (& C 63))) ) ) ) ) ) ) ) )
(test
   "cGxlYXN1cmUu"
   (base64 "pleasure.") )
(test
   "bGVhc3VyZS4="
   (base64 "leasure.") )
(test
   "ZWFzdXJlLg=="
   (base64 "easure.") )
(test
   "YXN1cmUu"
   (base64 "asure.") )
(test
   "c3VyZS4="
   (base64 "sure.") )

Pike

string icon = Protocols.HTTP.get_url_data("http://rosettacode.org/favicon.ico");
// The default base64 encodeing linefeeds every 76 chars
array encoded_lines = MIME.encode_base64(icon)/"\n";
// For brivety, just print the first and last line
write("%s\n...\n%s\n", encoded_lines[0], encoded_lines[-1]);
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
...
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

PowerShell

$webClient = [Net.WebClient]::new()
$bytes = $webClient.DownloadData('http://rosettacode.org/favicon.ico')
 
$output = [Convert]::ToBase64String($bytes)
 
$output
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

PureBasic

InitNetwork()
 
*BufferRaw = ReceiveHTTPMemory("http://rosettacode.org/favicon.ico")
If *BufferRaw
	Debug Base64Encoder(*BufferRaw, MemorySize(*BufferRaw))
Else
	Debug "Download failed"
EndIf

Python

Python 2

import urllib
import base64

data = urllib.urlopen('http://rosettacode.org/favicon.ico').read()
print base64.b64encode(data)

(For me this gets the wrong data; the data is actually an error message. But still, it base-64 encodes it.)

Python 3

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.

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))

Output:

#"AAABAAIAEBAAAAAAAABoBQAA...AQAAAAE=\r\n"

Raku

(formerly Perl 6)

sub MAIN {
    my $buf = slurp("./favicon.ico", :bin);
    say buf-to-Base64($buf);
}

my @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';

sub buf-to-Base64($buf) {
    join '', gather for $buf.list -> $a, $b = [], $c = [] {
        my $triplet = ($a +< 16) +| ($b +< 8) +| $c;
        take @base64map[($triplet +> (6 * 3)) +& 0x3F];
        take @base64map[($triplet +> (6 * 2)) +& 0x3F];
        if $c.elems {
            take @base64map[($triplet +> (6 * 1)) +& 0x3F];
            take @base64map[($triplet +> (6 * 0)) +& 0x3F];
        }
        elsif $b.elems {
            take @base64map[($triplet +> (6 * 1)) +& 0x3F];
            take '=';
        }
        else { take '==' }
    }
}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAA...QAAAAEAAAABAAAAAQAAAAE=

Red

Red [Source: https://github.com/vazub/rosetta-red]

print enbase read/binary https://rosettacode.org/favicon.ico
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

REXX

Some computers   (or REXX implementations)   are limited in virtual memory, so the   chunk   size (below) is
specified as   20000   to show how the file   (if specified)   can be read in chunks instead of reading it whole.

A much higher value for   chunk   could be used for modern systems or implementations.

/*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.*/
chunk= 20000                                     /*# of bytes to read a file at one time*/
                                                 /*If @ isn't a blank, then use CL text.*/
if @=''  then do s=1  by chunk  until y==''      /* " " is    "   "      "   "  the file*/
              y= charin(iFID, s, chunk)          /*read a chunk of the file, assign to Y*/
              @= @ || y                          /*append the chunk  (Y)  to the  @  var*/
              end   /*s*/                        /* [↑]  read a chunk of the file ──► @ */
t= base64(@)                                     /*convert the   @   string to  base 64.*/
say center(' input', 79, "─");     say @         /*show the header and the  input  text.*/
say center('base64', 79, "─");     say t         /*  "   "     "    "   "   base64   "  */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
base64: procedure;  parse arg Q;   $=            /*obtain input string;  and nullify $. */
        z= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

            do i=0  for 64                       /*process each char in the  Z  string. */
            !.i= substr(z,  i + 1,  1)           /*assign a char of  Z  to a  !  element*/
            end   /*i*/

        b= x2b( c2x(Q) )0000000000000000         /*Q ──► binary,  add some zero padding.*/
        L= length(Q) * 8                         /*compute   Q's   length  (in bits).   */

            do j=1  by 6  to L                   /*traipse through bit string by six.   */
            _= x2d( b2x( substr(b, j, 6) ) )     /*compute index into the BASE64 table. */
            $= $ || !._                          /*append to   $   (the output string). */
            end   /*j*/
                                                 /* [↓]  maybe append equal signs to $. */
        return $ || copies('=', 2 * (L//6==2) + (L//6==4) )

For the various outputs, several input texts from the Wikipedia article on   Base64   [1]   were used to demonstrate how padding works.

output   when using the input of:   , any carnal pleasure.
──────────────────────────────────── input─────────────────────────────────────
any carnal pleasure.
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhc3VyZS4=
output   when using the input of:   , any carnal pleasure
──────────────────────────────────── input─────────────────────────────────────
any carnal pleasure
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhc3VyZQ==
output   when using the input of:   , any carnal pleasur
──────────────────────────────────── input─────────────────────────────────────
any carnal pleasur
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhc3Vy
output   when using the input of:   , any carnal pleasu
──────────────────────────────────── input─────────────────────────────────────
any carnal pleasu
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhc3U=
output   when using the input of:   , any carnal pleas
──────────────────────────────────── input─────────────────────────────────────
any carnal pleas
────────────────────────────────────base64─────────────────────────────────────
YW55IGNhcm5hbCBwbGVhcw==

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()
Output:
bXkgc3RyaW5n
my string

RPL

Works with: RPL version 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 +
» 'STR→BITS' STO     @ ( "string" → fill "bits" )

« BIN 8 STWS STR→BITS
  "" 
  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 +
» '→B64' STO
"Hello, RPL!" →B64 
"To err is human, but to really foul things up you need a computer.\n    -- Paul R. Ehrlich" →B64
Output:
2: "SGVsbG8sIFJQTCEA==" 
1:"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="

Ruby

require 'open-uri'
require 'base64'

puts Base64.encode64 open('http://rosettacode.org/favicon.ico') {|f| f.read}

Scala

import java.net.URL
import java.util.Base64

object Base64S extends App {
  val conn = new URL("http://rosettacode.org/favicon.ico").openConnection
  val bytes = conn.getInputStream.readAllBytes()

  val result = Base64.getEncoder.encodeToString(bytes)
  println(s"${result.take(22)} ... ${result.drop(4830)}")

  assert(Base64.getDecoder.decode(result) sameElements bytes)

  println(s"Successfully completed without errors. [total ${compat.Platform.currentTime - executionStart} ms]")
}

Seed7

The Seed7 library encoding.s7i defines the function toBase64, which encodes a string with the Base64 encoding.

$ include "seed7_05.s7i";
  include "gethttp.s7i";
  include "encoding.s7i";

const proc: main is func
  begin
    writeln(toBase64(getHttp("rosettacode.org/favicon.ico")));
  end func;

SenseTalk

put "To err is human, but to really foul things up you need a computer. --Paul R.Ehrlich" as base64
put base64Encode ("To err is human, but to really foul things up you need a computer. --Paul R.Ehrlich")

Output:

VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVk
IGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=
...
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVk
IGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=

Sidef

var data = %f'favicon.ico'.read(:raw)   # binary string
print data.encode_base64                # print to STDOUT

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))

Output:

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==

Standard ML

Using smlnj-lib:

fun b64enc filename =
  let
    val instream = BinIO.openIn filename
    val data = BinIO.inputAll instream
  in
    Base64.encode data before BinIO.closeIn instream
  end
Output:
- b64enc "/tmp/favicon.ico";
val it =
  "AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNg#"
  : string

Note the "#" means the output is truncated.

Tcl

Works with: Tcl version 8.6
package require Tcl 8.6
package require http

set tok [http::geturl http://rosettacode.org/favicon.ico]
set icondata [http::data $tok]
http::cleanup $tok

puts [binary encode base64 -maxlen 64 $icondata]

With older versions of Tcl, the base64 encoding is best supported via an external package:

Library: Tcllib (Package: base64)
package require base64
package require http

set tok [http::geturl http://rosettacode.org/favicon.ico]
set icondata [http::data $tok]
http::cleanup $tok

puts [base64::encode -maxlen 64 $icondata]

VBA

Option Explicit
Public Function Decode(s As String) As String
    Dim i As Integer, j As Integer, r As Byte
    Dim FirstByte As Byte, SecndByte As Byte, ThirdByte As Byte
    Dim SixBitArray() As Byte, ResultString As String, Token As String
    Dim Counter As Integer, InputLength As Integer
    InputLength = Len(s)
    ReDim SixBitArray(InputLength + 1)
    j = 1 'j counts the tokens excluding cr, lf and padding
    For i = 1 To InputLength 'loop over s and translate tokens to 0-63
        Token = Mid(s, i, 1)
        Select Case Token
            Case "A" To "Z"
                SixBitArray(j) = Asc(Token) - Asc("A")
                j = j + 1
            Case "a" To "z"
                SixBitArray(j) = Asc(Token) - Asc("a") + 26
                j = j + 1
            Case "0" To "9"
                SixBitArray(j) = Asc(Token) - Asc("0") + 52
                j = j + 1
            Case "+"
                SixBitArray(j) = 62
                j = j + 1
            Case "/"
                SixBitArray(j) = 63
                j = j + 1
            Case "="
                'padding'
            Case Else
                'cr and lf
        End Select
    Next i
    r = (j - 1) Mod 4
    Counter = 1
    For i = 1 To (j - 1) \ 4 'loop over the six bit byte quadruplets
        FirstByte = SixBitArray(Counter) * 4 + SixBitArray(Counter + 1) \ 16
        SecndByte = (SixBitArray(Counter + 1) Mod 16) * 16 + SixBitArray(Counter + 2) \ 4
        ThirdByte = (SixBitArray(Counter + 2) Mod 4) * 64 + SixBitArray(Counter + 3)
        ResultString = ResultString & Chr(FirstByte) & Chr(SecndByte) & Chr(ThirdByte)
        Counter = Counter + 4
    Next i
    Select Case r
        Case 3
            FirstByte = SixBitArray(Counter) * 4 + SixBitArray(Counter + 1) \ 16
            SecndByte = (SixBitArray(Counter + 1) Mod 16) * 16 + SixBitArray(Counter + 2) \ 4
            ResultString = ResultString & Chr(FirstByte) & Chr(SecndByte)
        Case 2
            FirstByte = SixBitArray(Counter) * 4 + SixBitArray(Counter + 1) \ 16
            ResultString = ResultString & Chr(FirstByte)
    End Select
    Decode = ResultString
End Function
Public Function Encode(s As String) As String
    Dim InputLength As Integer, FirstByte As Byte, SecndByte As Byte, ThirdByte As Byte, r As Byte
    Dim LineNumber As Integer, z As Integer, q() As String, ResultString As String
    Dim FullLines As Integer, LastLineLength As Integer, Counter As Integer
    q = Split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j," & _
        "k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,+,/", ",", -1, vbTextCompare)
    InputLength = Len(s)
    r = InputLength Mod 3
    FullLines = ((InputLength - r) / 3) \ 20 + 1: LastLineLength = (InputLength - r) / 3 Mod 20 - 1
    Counter = 1
    For LineNumber = 1 To FullLines
        For z = 0 To IIf(LineNumber < FullLines, 19, LastLineLength) 'loop over the byte triplets
            FirstByte = Asc(Mid(s, Counter, 1))
            SecndByte = Asc(Mid(s, Counter + 1, 1))
            ThirdByte = Asc(Mid(s, Counter + 2, 1))
            Counter = Counter + 3
            ResultString = ResultString & q(FirstByte \ 4) & q((FirstByte Mod 4) * 16 + _
                (SecndByte \ 16)) & q((SecndByte Mod 16) * 4 + (ThirdByte \ 64)) & q(ThirdByte Mod 64)
        Next z
        If LineNumber < FullLines Then ResultString = ResultString & vbCrLf
    Next LineNumber
    Select Case r
        Case 2
            FirstByte = Asc(Mid(s, Counter, 1))
            SecndByte = Asc(Mid(s, Counter + 1, 1))
            ResultString = ResultString & q(FirstByte \ 4) & q((FirstByte Mod 4) * 16 + _
                (SecndByte \ 16)) & q((SecndByte Mod 16) * 4) & "="
        Case 1
            FirstByte = Asc(Mid(s, Counter, 1))
            ResultString = ResultString & q(FirstByte \ 4) & q((FirstByte Mod 4) * 16) & "=="
    End Select
    Encode = ResultString
End Function
Private Function ReadWebFile(ByVal vWebFile As String) As String
    'adapted from https://www.ozgrid.com/forum/forum/help-forums/excel-general/86714-vba-read-text-file-from-a-url
    Dim oXMLHTTP As Object, i As Long, vFF As Long, oResp() As Byte
    Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
    oXMLHTTP.Open "GET", vWebFile, False
    oXMLHTTP.send
    Do While oXMLHTTP.readyState <> 4: DoEvents: Loop
    oResp = oXMLHTTP.responseBody 'Returns the results as a byte array
    ReadWebFile = StrConv(oResp, vbUnicode)
    Set oXMLHTTP = Nothing
End Function
Public Sub Task()
    Dim In_ As String, Out As String, bIn As String
    Dim filelength As Integer
    Dim i As Integer
    In_ = ReadWebFile("http://rosettacode.org/favicon.ico")
    Out = Encode(In_)
    bIn = Decode(Out)
    Debug.Print "The first eighty and last eighty characters after encoding:"
    Debug.Print Left(Out, 82) & "..." & vbCrLf & Join(Split(Right(Out, 82), vbCrLf), "")
    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
Output:
The first eighty and last eighty characters after encoding:

AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB ... AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE= Result of string comparison of input and decoded output: 0.

A zero indicates both strings are equal.

V (Vlang)

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!")}
}

Wren

Library: Wren-fmt
Library: Wren-seq

From first principles using string manipulation. Quick enough here.

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()
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZ
....
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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.

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);
]
Output:
AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
...
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=

zkl

Using shared libraries for cURL and message hashing:

var [const] MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl");
 
icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0)
icon=icon[0][icon[1],*];	// remove header
b64:=MsgHash.base64encode(icon);
println("Is the Rosetta Code icon the same (byte for byte) encoded then decoded: ",
   icon==MsgHash.base64decode(b64));
b64.println();
b64.text.println();
Output:

Encoded to 72 characters per line

Is the Rosetta Code icon the same (byte for byte) encoded then decoded: True
Data(4,920)
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA
AAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAE=
Cookies help us deliver our services. By using our services, you agree to our use of cookies.