CloudFlare has suffered a massive security issue affecting all of its customers, including Rosetta Code. I will be expiring all passwords and session cookies sometime Friday, February 24th. Cookie longevity will also be reduced for 30 days. --Michael Mol (talk) 04:56, 24 February 2017 (UTC)

Base64 encode data

From Rosetta Code
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.

ABAP[edit]

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=

ALGOL 68[edit]

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=

C[edit]

libresolv[edit]

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[edit]

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++[edit]

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

C#[edit]

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=

D[edit]

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[edit]

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.

Elixir[edit]

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

Erlang[edit]

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

Go[edit]

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

Manual implementation[edit]

 
// 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"
)
 
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 bytes.Buffer
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 bytes.Buffer
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)
}
 

Haskell[edit]

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 =
case C.null stream of
True -> C.empty
_ ->
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 $ map (uncurry shiftL) $ zip (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
 

J[edit]

Solution (standard library):
   load'convert/misc/base54'  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[edit]

Code ported from C solution. Can also use org.apache.commons.codec.binary.Base64 from Apache Commons Codec

package org.rosettacode;
 
import java.io.IOException;
import java.io.InputStream;
 
public class Base64
{
static String base64 (final InputStream is) throws IOException
{
final char[] alpha = { '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', '+', '/' };
final StringBuilder sb = new StringBuilder ();
final byte c[] = new byte[4];
long u;
int len;
int w = 0;
 
do
{
c[1] = c[2] = 0;
 
if ( (len = is.read (c, 0, 3)) == 0)
break;
u = ( ((long) c[0]) << 16) | ( ((long) c[1]) << 8) | c[2];
 
sb.append (alpha[(int) ( (u >> 18) & 63)]);
sb.append (alpha[(int) ( (u >> 12) & 63)]);
sb.append (len < 2 ? '=' : alpha[(int) (u >> 6) & 63]);
sb.append (len < 3 ? '=' : alpha[(int) u & 63]);
 
if (++w == 19)
{
w = 0;
sb.append ('\n');
}
}
while (len == 3);
 
if (w > 0)
sb.append ('\n');
 
return sb.toString ();
}
public static void main (final String[] args)
{
// Seems like this should work, but you'll get a 403 error (Forbidden)
// try (InputStream is = new URL("http://rosettacode.org/favicon.ico").openStream ())
 
// this will load the file if it's in the same package as the class itself
try (InputStream is = Base64.class.getResourceAsStream("favicon.ico"))
{
System.out.println (Base64.base64 (is));
}
catch (final IOException e)
{
e.printStackTrace (System.err);
}
}
}
 
AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=

Java 8 version[edit]

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);
}
}
AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=

JavaScript[edit]

(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)[edit]

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[edit]

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.
});
}
 

Lasso[edit]

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[edit]

put URL "http://rosettacode.org/favicon.ico" into rosettaico
put base64encode(rosettaico)
 
Ouput
AAABAA...S0tLS0tLS0t...QAAAAE=

Mathematica / Wolfram Language[edit]

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

Very interesting results.

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

Objective-C[edit]

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;
}

Perl[edit]

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

Perl 6[edit]

sub MAIN {
my $buf = slurp("/tmp/favicon.ico", :bin);
say buf-to-Base64($buf);
}
 
my @base64map = '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=

Phix[edit]

As this is a draft task, I've gone with the example from wp, for now. Pete Lomax (talk) 10:25, 11 September 2015 (UTC)

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:
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1p
bmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhl
bWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=
"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."

PHP[edit]

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

PicoLisp[edit]

(setq *Char64
(chop
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ) )
(de encode64 (L)
(let? A (car L)
(make
(link (get *Char64 (inc (>> 2 A))))
(nond
((cadr L)
(link
(get *Char64 (inc (>> -4 (& A 3))))
'=
'= ) )
((caddr L)
(link
(get
*Char64
(inc
(|
(>> -4 (& A 3))
(>> 4 (cadr L)) ) ) )
(get
*Char64
(inc (>> -2 (& (cadr L) 15))) )
'= ) )
(NIL
(link
(get
*Char64
(inc
(|
(>> -4 (& A 3))
(>> 4 (cadr L)) ) ) )
(get
*Char64
(inc
(|
(>> -2 (& (cadr L) 15))
(>> 6 (caddr L)) ) ) )
(get *Char64 (inc (& (caddr L) 63))) ) ) ) ) ) )
(de base64 (S)
(let S (mapcar char (chop S))
(pack
(make
(while (cut 3 'S)
(chain (encode64 @)) ) ) ) ) )
(test
"cGxlYXN1cmUu"
(base64 "pleasure.") )
(test
"bGVhc3VyZS4="
(base64 "leasure.") )
(test
"ZWFzdXJlLg=="
(base64 "easure.") )
(test
"YXN1cmUu"
(base64 "asure.") )
(test
"c3VyZS4="
(base64 "sure.") )

Python[edit]

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

Racket[edit]

 
#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"
 

REXX[edit]

/*REXX program converts  text  (from a file or CL)  to a base64 text string.  */
parse arg iFID @ /*get optional arguments from the C.L. */
if iFID=='' then iFID='favicon.ico' /*use default name of the input file. */
chunk=10000 /*# of bytes to read a file at one time*/
/* [↓] read the input file ──► @ */
if @='' then do s=1 by chunk until y==''; y=charin(iFID,s,chunk); @=@||y
end /*s*/
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 x; $= /*get the input string; and nullify $. */
z='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
do i=0 for 64;  !.i=substr(z,i+1,1); end /*assign the array.*/
b=x2b(c2x(x))0000000000000000 /*X──►binary, add some zero (0) padding*/
L=length(x)*8 /*save B length (in bits) for later.*/
 
do j=1 by 6 to L /*traipse through bit string by 6.*/
_=x2d( b2x( substr(b, j, 6) )) /*compute index into BASE64 table.*/
$=$ || !._ /*append to $ (the output string).*/
end /*j*/
 
return $||copies('=', 2*(L//6==2)+(L//6==4)) /*Append equal signs (=)?*/

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

Ruby[edit]

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

Seed7[edit]

$ 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;

Sidef[edit]

var base64 = frequire('MIME::Base64');
 
var file = %f'favicon.ico';
file.open('<:raw', \var fh);
 
print base64.encode_base64(fh.slurp);

Tcl[edit]

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]

zkl[edit]

Using shared libraries for cURL and message hashing:

var 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);
b64.println();
b64.text.println();
Output:

Encoded to 72 characters per line

Data(4,920)
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA
AAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm
...
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAAB
AAAAAQAAAAEAAAABAAAAAQAAAAE=