Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Base64 encode data

From Rosetta Code
Base64 encode data is adraft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in itstalk page.

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

See alsoBase64 decode data.

ABAP

DATA:li_clientTYPE REF TOif_http_client,lv_encodedTYPEstring,lv_dataTYPExstring.cl_http_client=>create_by_url(EXPORTINGurl='http://rosettacode.org/favicon.ico'IMPORTINGclient=li_client).li_client->send().li_client->receive().lv_data=li_client->response->get_data().CALL FUNCTION'SSFC_BASE64_ENCODE'EXPORTINGbindata=lv_dataIMPORTINGb64data=lv_encoded.WHILEstrlen(lv_encoded)>100.WRITE:/lv_encoded(100).lv_encoded=lv_encoded+100.ENDWHILE.WRITE:/lv_encoded.
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAA...AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Action!

Library:Action! Tool Kit
INCLUDE "D2:IO.ACT" ;from the Action! Tool KitPROC 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)  FIRETURNPROC 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
withAda.Text_IO;withAWS.Response;withAWS.Client;withAWS.Translator;procedureEncode_AWSisURL:constantString:="http://rosettacode.org/favicon.ico";Page:constantAWS.Response.Data:=AWS.Client.Get(URL);Payload:constantString:=AWS.Response.Message_Body(Page);Icon_64:constantString:=AWS.Translator.Base64_Encode(Payload);beginAda.Text_IO.Put_Line(Icon_64);endEncode_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 outputAAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEAB...AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

ARM Assembly

.section .rodatach64: .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, r0be_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_cyclebe_store2:    mov r3, #'='    strb r3, [r0]    add r0, r0, #1be_store1:    mov r3, #'='    strb r3, [r0]    add r0, r0, #1be_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, r0bd_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_cycleexit:    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, lrcd_digit:    adds r0, r0, #17    blt cd_ps    add r0, r0, #52    mov pc, lrcd_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=

Batch File

Downloadinghttps://rosettacode.org/favicon.ico using commandline
certutil -urlcache -split -f favicon.ico https://rosettacode.org/favicon.ico

^ Would be mistakenly quarantined as threatTrojan:Win32/Ceprolad.A by Windows Security (at least in Windows 10/11).

Usingpowershell orpwsh:

powershell/pwsh -command "iwr https://rosettacode.org/favicon.ico -OutFile favicon.ico"

Usingcurl (natively available in Windows 10 Insider build 17063 and later[1]:

curl --output favicon.ico https://rosettacode.org/favicon.ico

Downloading the file usingbitsadmin would not work (insufficient file content).

Encoding the file as Base64

This script assumesfavicon.ico exists in the current working directory.

@echo offsetlocal enableextensionsset"_t=%temp%\favicon.tmp"::using certutil -encodehex undocumented param to encode as Base64::https://www.dostips.com/forum/viewtopic.php?f=3&t=85211>&2 certutil -f -encodehex favicon.ico"%_t%" 1073741825||goto:eof %= 0x40000000 | 0x1 =%type"%_t%"del"%_t%"
Output:
$ favicon.bat 2>nulAAABAAMAMDAAAAEAIA...D8PwAA/D8AAPw/AAA=

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>intmain(){intfin=open("favicon.ico",O_RDONLY);if(fin==-1)return1;structstatst;if(fstat(fin,&st))return1;void*bi=mmap(0,st.st_size,PROT_READ,MAP_PRIVATE,fin,0);if(bi==MAP_FAILED)return1;intoutLength=((st.st_size+2)/3)*4+1;char*outBuffer=malloc(outLength);if(outBuffer==NULL)return1;intencodedLength=b64_ntop(bi,st.st_size,outBuffer,outLength);if(encodedLength<0)return1;puts(outBuffer);free(outBuffer);munmap(bi,st.st_size);close(fin);return0;}

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 commonbase64 utility program, though much less efficiently.

#include<stdio.h>#include<unistd.h>typedefunsignedlongUL;intmain(void){constchar*alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ""abcdefghijklmnopqrstuvwxyz""0123456789+/";unsignedcharc[4];ULu,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');return0;}

C#

namespaceRosettaCode.Base64EncodeData{usingSystem;usingSystem.Net;internalstaticclassProgram{privatestaticvoidMain(){conststringpath="http://rosettacode.org/favicon.ico";byte[]input;using(varclient=newWebClient()){input=client.DownloadData(path);}varoutput=Convert.ToBase64String(input);Console.WriteLine(output);}}}

Output:

AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

C++

#include<iostream>#include<fstream>#include<vector>typedefunsignedcharbyte;usingnamespacestd;constunsignedm1=63<<18,m2=63<<12,m3=63<<6;classbase64{public:base64(){char_set="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";}stringencode(vector<byte>v){stringres;unsignedd,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,'=');}elseif(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);}returnres;}private:stringchar_set;};intmain(intargc,char*argv[]){base64b;basic_ifstream<byte>f("favicon.ico",ios::binary);stringr=b.encode(vector<byte>((istreambuf_iterator<byte>(f)),istreambuf_iterator<byte>()));copy(r.begin(),r.end(),ostream_iterator<char>(cout));return0;}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZ...AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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.

100printchr$(247);chr$(14);110dima$(63):remalphabet120dimi(2):reminputbytes130dimo$(3):remoutputcharacters140fori=0to25150:a$(i)=chr$(asc("A")+i)160:a$(26+i)=chr$(asc("a")+i)170:ifi<10thena$(52+i)=chr$(asc("0")+i)180nexti190a$(62)="+"200a$(63)="/"210p$="=":rempaddingchar220input"source file";s$230open1,8,2,s$+",p":ifstthen450240input"dest file";d$250open2,8,3,d$+",s,w":ifstthen450260ford=0to1step0:remwhilenotd(one)270:p=0:foro=0to3:o$(o)=p$:nexto280:fori=0to2290:i(i)=0300:ifdthen330310:get#1,i$:iflen(i$)theni(i)=asc(i$)320:ifstand64thenp=2-i:d=1330:nexti340:o$(0)=a$((i(0)and252)/4)350:o$(1)=a$((i(0)and3)*16+(i(1)and240)/16)360:ifp<2theno$(2)=a$((i(1)and15)*4+(i(2)and192)/64)370:ifp<1theno$(3)=a$(i(2)and63)380:foro=0to3:printo$(o);:print#2,o$(o);:nexto390:c=c+4:ifc>=76thenc=0:print:print#2,chr$(13);400nextd410print:print#2,chr$(13);420close1430close2440end450print"error:"st460open15,8,15:input#15,ds,ds$,a,b:close15470printds,ds$,a,b
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EA...AOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA/////wAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Common Lisp

A nice example for the CL eco system usingcl-base64 anddrakma.

(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(defunbase64-encode(&optional(uri"https://rosettacode.org/favicon.ico"))"Returns the BASE64 encoded string of the file at URI."(let*((input(http-requesturi:want-streamt))(output(loopwitharray=(make-array0:element-type'unsigned-byte:adjustablet:fill-pointer0)fordata-chunk=(read-byteinputnilnil)whiledata-chunkdo(vector-push-extenddata-chunkarray)finally(return(usb8-array-to-base64-stringarray)))))(closeinput)output))
Output:
"AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///...

Crystal

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


D

voidmain(){importstd.stdio,std.base64,std.net.curl,std.string;constf="http://rosettacode.org/favicon.ico".get.representation;Base64.encode(f).writeln;}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAwqgIAADCjgUAACgAAAAQAAAAIAA...AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQ==

Delphi

programBase64EncodeData;{$APPTYPE CONSOLE}usesIdHTTP,IdCoderMIME;varlSrcString:string;lHTTP:TIdHTTP;beginlHTTP:=TIdHTTP.Create(nil);trylSrcString:=lHTTP.Get('http://rosettacode.org/favicon.ico');Writeln(TIdEncoderMIME.EncodeString(lSrcString));finallylHTTP.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}$'AAABAAIAEBAAAAAAAABoAAEAAAABAAAAAQAAAAE=

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 algoBase64_decode_data#Ed for implementation details/quirks.

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

Elixir

data=File.read!("favicon.ico")encoded=:base64.encode(data)IO.putsencoded
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
openSystemopenSystem.Netleturl="https://rosettacode.org/favicon.ico"letdownload(url:string)=useclient=newWebClient()client.DownloadDataurlletraw=downloadurlletencoded=Convert.ToBase64Stringrawprintfn"%s"encoded
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAA ...

Manual Implementation

Works with:fsharp version 4.5
openSystem.Netletencodes=letchars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".ToCharArray()|>Array.mapstringletpaddingSize=letc=Array.lengths%3ifc=0then0else3-clets=Array.appends(Array.replicatepaddingSize(byte'\x00'))|>Array.mapintletcalcc=letn=(s.[c]<<<16)+(s.[c+1]<<<8)+s.[c+2]letn1=(n>>>18)&&&63letn2=(n>>>12)&&&63letn3=(n>>>6)&&&63letn4=n&&&63chars.[n1]+chars.[n2]+chars.[n3]+chars.[n4][0..3..Array.lengths-1]|>List.mapcalc|>List.reduce(+)|>funr->r.Substring(0,String.lengthr-paddingSize)+String.replicatepaddingSize"="leturl="https://rosettacode.org/favicon.ico"letdownload(url:string)=useclient=newWebClient()client.DownloadDataurlletencoded=url|>download|>encodeprintfn"%s"encoded
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAA ...

Factor

USING:base64http.clientiokernelstrings;"http://rosettacode.org/favicon.ico"http-getnip>base64-lines>stringprint
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

variablebitsbuff:alphabase( u -- c )$3FandC"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"1++c@;:storecode( u f -- )ifdrop'='elsealphabasethenc,;:3bytesin( addrf addr -- n )$0bitsbuff!30dodupI+c@bitsbuff@8lshift+bitsbuff!loop-;:4chars,( n -- )( n=# of bytes )40dodupI-0<bitsbuff@18rshiftswapstorecodebitsbuff@6lshiftbitsbuff!loopdrop;:b64enc( addr1 n1 -- addr2 n2 )hererotrot( addr2 addr1 n1 )over+duprot( addr2 addr1+n1 addr1+n1 addr1 )dodupI3bytesin4chars,3+loopdrop( addr2 )duphereswap-( addr2 n2 );
Output:
s" favicon.ico" slurp-file b64enc cr type    AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAA(.../...)AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE= oks" any carnal pleasure." b64enc cr type YW55IGNhcm5hbCBwbGVhc3VyZS4= oks" 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.

programdemo_base64! base64-encode data to RFC-4648 and print to standard output! usage: base64 inputfile > outputfileuse,intrinsic::iso_fortran_env,only:stderr=>ERROR_UNIT,stdout=>OUTPUT_UNITuse,intrinsic::iso_fortran_env,only:int32implicit noneinteger(kind=int32)::i,j,column,sz,pad,iostatcharacter(len=1),allocatable::text(:)character(len=:),allocatable::infilecharacter(len=4)::chunkinteger,parameter::rfc4648_linelength=76character(len=1),parameter::rfc4648_padding='='infile=get_arg(1)! allocate array and copy file into it and pad with two characters at endcallslurp(infile,text)! figure out how many characters at end are pad characterssz=size(text)-2pad=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 bitsdoi=1,sz,3chunk=three2four(text(i:i+2))if(i.gt.sz-3)then! if at end put any pad characters in placeif(pad.gt.0.and.pad.lt.3)thenchunk(5-pad:)=repeat(rfc4648_padding,pad)endif      endif      if(column.ge.rfc4648_linelength)then         write(stdout,'(a)')flush(unit=stdout,iostat=iostat)column=0endif      write(stdout,'(a)',advance='no')chunkcolumn=column+4enddo   if(column.ne.0)write(stdout,'(a)')containsfunctionthree2four(tri)result(quad)character(len=1),intent(in)::tri(3)character(len=4)::quadinteger(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.doj=0,3callmvbits(i32,(j)*6,6,iout(4-j),0)k=4-jquad(k:k)=rfc4648_alphabet(iout(k)+1:iout(k)+1)enddoend functionthree2fourfunctionget_arg(iarg)result(value)! get nth argument from command lineinteger,intent(in)::iargcharacter(len=:),allocatable::valueinteger::argument_length,istatcallget_command_argument(number=iarg,length=argument_length)if(allocated(value))deallocate(value)allocate(character(len=argument_length)::value)value(:)=''callget_command_argument(iarg,value,status=istat)end functionget_argsubroutineslurp(filename,text)! allocate text array and read file filename into it, padding on two characterscharacter(len=*),intent(in)::filenamecharacter(len=1),allocatable,intent(out)::text(:)integer::nchars=0,igetunit,iostat=0,icharacter(len=256)::iomsgcharacter(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 charactersread(igetunit,iostat=iostat,iomsg=iomsg)text(:nchars)! load input file -> text arrayif(iostat/=0)stop'*slurp* bad read of '//trim(filename)//':'//trim(iomsg)text(size(text)-1:)=repeat(achar(0),2)! init padding charactersclose(iostat=iostat,unit=igetunit)! close if opened successfully or notend subroutineslurpend programdemo_base64
Output:

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

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


FreeBASIC

DimSharedAsStringB64B64="ABCDEFGHIJKLMNOPQRSTUVWXYZ"&_"abcdefghijklmnopqrstuvwxyz"&_"0123456789+/"#defineE0(v1)v1Shr2#defineE1(v1,v2)((v1And3)Shl4)+(v2Shr4)#defineE2(v2,v3)((v2And&H0F)Shl2)+(v3Shr6)#defineE3(v3)(v3And&H3F)FunctionEncode64(SAsString)AsStringDimAsIntegerj,k,l=Len(S)DimAsStringmEIfl=0ThenReturnmEmE=String(((l+2)\3)*4,"=")Forj=0Tol-((lMod3)+1)Step3mE[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+=4NextjIf(lMod3)=2ThenmE[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]=61Elseif(lMod3)=1ThenmE[k+0]=B64[e0(S[j+0])]mE[k+1]=B64[e1(S[j+0],S[j+1])]mE[k+2]=61mE[k+3]=61EndIfReturnmEEndFunctionDimAsStringmsg64="To err is human, but to really foul things up you need a computer."&_Chr(10)&"    -- Paul R. Ehrlich"Printmsg64Print:Print(Encode64(msg64))Sleep
Output:
To err is human, but to really foul things up you need a computer.    -- Paul R. EhrlichVG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=

Frink

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


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 = encodedBase64Strlocal fn DecodeBase64String( base64String as CFStringRef ) as CFStringRef  CFStringRef decodedString = NULL  CFDataRef encodedData  = fn DataWithBase64EncodedString( base64String, NSDataBase64DecodingIgnoreUnknownCharacters )  decodedString = fn StringWithData( encodedData, NSUTF8StringEncoding )end fn = decodedStringCFStringRef originalString, encodedBase64String, decodedBase64StringoriginalString = @"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:VGhpcyBpcyBhIHRlc3Qgc3RyaW5nIHRvIGJlIGVuY29kZWQgYXMgQmFzZTY0IGFuZCB0aGVuIGRlY29kZWQuThis is the Base64 string decoded:This is a test string to be encoded as Base64 and then decoded.


Go

Standard Library

packagemainimport("encoding/base64""fmt""io/ioutil""net/http")funcmain(){r,err:=http.Get("http://rosettacode.org/favicon.ico")iferr!=nil{fmt.Println(err)return}deferr.Body.Close()d,err:=ioutil.ReadAll(r.Body)iferr!=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 | ./base64packagemainimport("bytes""fmt""io/ioutil""log""os""strings")const(B64_CHUNK_SIZE=76)typeULint64// Our lookup table.varalphastring="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"// Base64 encode a raw byte stream.funcB64Encode(raw[]byte)(string,error){varbufferstrings.Buildervarreader*bytes.ReadervaruUL// w ULvarlengthintvarchunk[]bytevarerrerrorlength=3reader=bytes.NewReader(raw)chunk=make([]byte,3)forlength==3{chunk[1]=0chunk[2]=0length,err=reader.Read(chunk)iferr!=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]))iflength<2{buffer.WriteString("=")}else{buffer.WriteString(string(alpha[u>>6&63]))}iflength<3{buffer.WriteString("=")}else{buffer.WriteString(string(alpha[u&63]))}}returnbuffer.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.funcB64EncodePretty(raw[]byte)(string,error){varbufferstrings.Builderencoded,err:=B64Encode(raw)iferr!=nil{return"",err}length:=len(encoded)chunks:=int(length/B64_CHUNK_SIZE)+1fori:=0;i<chunks;i++{chunk:=i*B64_CHUNK_SIZEend:=chunk+B64_CHUNK_SIZEifend>length{end=chunk+(length-chunk)}buffer.WriteString(encoded[chunk:end]+"\n")}returnbuffer.String(),err}funcmain(){contents,err:=ioutil.ReadAll(os.Stdin)iferr!=nil{log.Fatal("Error reading input: ",err)}encoded,err:=B64EncodePretty(contents)iferr!=nil{log.Fatal("Error base64 encoding the input: ",err)}fmt.Printf("%s",encoded)}
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EA...AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

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 #-}moduleMainwhereimportData.BitsimportData.CharimportqualifiedData.ByteString.Char8asC-- | alphaTable: Our base64 lookup table.alphaTable::C.ByteStringalphaTable="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"-- | b64Encode: Simple base64 encode function operating on normal C.ByteString'sb64Encode::C.ByteString->C.ByteStringb64Encodestream=ifC.nullstreamthenC.emptyelsealphaTable`C.index`shiftR_u18`C.cons`alphaTable`C.index`(shiftR_u12.&.63)`C.cons`(ifC.lengthchunk<2then'='elsealphaTable`C.index`(shiftR_u6.&.63))`C.cons`(ifC.lengthchunk<3then'='elsealphaTable`C.index`(_u.&.63))`C.cons`b64Encode(C.drop3stream)wherechunk=C.take3stream_u=uchunk-- | b64EncodePretty: Intersperses \n every 76 bytes for prettier outputb64EncodePretty::C.ByteString->C.ByteStringb64EncodePretty=makePretty76.b64Encode-- | u: base64 encoding magicu::C.ByteString->Intuchunk=fromIntegralresult::Intwhereresult=foldl(.|.)0$zipWithshiftL(C.foldr(\cacc->charToIntegerc:acc)[]chunk)[16,8,0]-- lazy foldl to fix formatting-- | charToInteger: Convert a Char to an IntegercharToInteger::Char->IntegercharToIntegerc=fromIntegral(ordc)::Integer-- | makePretty: Add new line characters throughout a character streammakePretty::Int->C.ByteString->C.ByteStringmakePretty_(C.uncons->Nothing)=C.emptymakePrettybystream=first`C.append`"\n"`C.append`makePrettybyrestwhere(first,rest)=C.splitAtbystreammain::IO()main=C.getContents>>=C.putStr.b64EncodePretty

Using Data.ByteString.Base64

importqualifiedData.ByteString.Base64asBase64(decode,encode)importqualifiedData.ByteString.Char8asB(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~b2B64padB64=:,'='#~021i.3|#b2B64=:BASE64{~_6#.\(8#2),@:#:a.&i.

Example:

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

Java

Java offers theBase64 class, which includes both theEncoder andDecoder classes.
The implementation supports RFC 4648 and RFC 2045.

The usage is very simple, supply abyte array, and it will return, either an encodedbyte array, or an ISO 8859-1 encodedString.

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

importjava.io.FileInputStream;importjava.io.IOException;importjava.util.Base64;
byte[]encodeFile(Stringpath)throwsIOException{try(FileInputStreamstream=newFileInputStream(path)){byte[]bytes=stream.readAllBytes();returnBase64.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.

AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAAADAAAABgAAAAAQAgAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...wv//AMH/hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPw/AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=


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

importjava.io.ByteArrayInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.URL;importjava.net.URLConnection;importjava.util.Arrays;publicclassBase64{privatestaticfinalchar[]alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();staticStringbase64(InputStreamis)throwsIOException{StringBuildersb=newStringBuilder();intblocks=0;while(true){intc0=is.read();if(c0==-1)break;intc1=is.read();intc2=is.read();intblock=((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');returnsb.toString();}privatestaticvoidassertBase64(Stringexpected,byte[]bytes)throwsIOException{Stringactual=base64(newByteArrayInputStream(bytes));if(!actual.equals(expected)){thrownewIllegalStateException(String.format("Expected %s for %s, but got %s.",expected,Arrays.toString(bytes),actual));}}privatestaticvoidtestBase64()throwsIOException{assertBase64("",newbyte[]{});assertBase64("AA==\n",newbyte[]{0});assertBase64("AAA=\n",newbyte[]{0,0});assertBase64("AAAA\n",newbyte[]{0,0,0});assertBase64("AAAAAA==\n",newbyte[]{0,0,0,0});assertBase64("/w==\n",newbyte[]{-1});assertBase64("//8=\n",newbyte[]{-1,-1});assertBase64("////\n",newbyte[]{-1,-1,-1});assertBase64("/////w==\n",newbyte[]{-1,-1,-1,-1});}publicstaticvoidmain(String[]args)throwsIOException{testBase64();URLConnectionconn=newURL("http://rosettacode.org/favicon.ico").openConnection();conn.addRequestProperty("User-Agent","Mozilla");// To prevent an HTTP 403 error.try(InputStreamis=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?functionstringToArrayUnicode(str){for(vari=0,l=str.length,n=[];i<l;i++)n.push(str.charCodeAt(i));returnn;}functiongenerateOnesByLength(n){//Attempts to generate a binary number full of ones given a length.. they don't redefine each other that much.varx=0;for(vari=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?}returnx;}functionpaf(_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..vara=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}functiontoBase64(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.vara=[],i,output=[];for(i=0x41;i<=0x5a;i++){//A-Za.push(String.fromCharCode(i));}for(i=0x61;i<=0x7A;i++){//a-za.push(String.fromCharCode(i));}for(i=0x30;i<=0x39;i++){//0-9a.push(String.fromCharCode(i));}a.push('+','/');varoffset=0,offsetLength=0,x;for(vari=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{vary=(6-offsetLength)/2;x=paf(offset,offsetLength,0);offset=x[0];output.push(a[x[2]]);switch(y){case2:output.push('=');//This thingy right here, you know.. the offsets also, no break statement;case1:output.push('=');break;}}}returnoutput.join('');//You can change it so the result is an array instead!!!!}//UsagereturntoBase64(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, seespec

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
varhttp=require('http');varoptions={host:'rosettacode.org',path:'/favicon.ico'};callback=function(response){varstr='';response.on('data',function(chunk){str+=chunk;});response.on('end',function(){console.log(newBuffer(str).toString('base64'));//Base64 encoding right here.});}

Jsish

Using a contributed entry that is a small change of the Jsilib/Jsi_Wget.jsi sources, to thehttpGet.jsi module. Stored as an attachment athttps://jsish.org/fossil/jsi/wiki/Wget and also listed atHTTP#Jsish.

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

jq

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

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
usingRequestsfile=read(get("https://rosettacode.org/favicon.ico"))encoded=base64encode(file)print(encoded)
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP[...]QAAAAE=

Kotlin

// version 1.1.2importjava.io.Fileimportjava.util.Base64funmain(args:Array<String>){valpath="favicon.ico"// already downloaded to current directoryvalbytes=File(path).readBytes()valbase64=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 rosettaicoput base64encode(rosettaico)OuputAAABAA...S0tLS0tLS0t...QAAAAE=

Lua

localdic="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"functionencode(t,f)localb1,b2,b3,b4b1=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))iff>1thenio.write(dic:sub(b3,b3))elseio.write("=")endiff>2thenio.write(dic:sub(b4,b4))elseio.write("=")endendlocali=assert(io.open("favicon.ico","rb"))localiconData=i:read("*all")localdataLen,s,t=#iconData,1while(dataLen>2)dot=(iconData:sub(s,s):byte()<<16);s=s+1t=t+(iconData:sub(s,s):byte()<<8);s=s+1t=t+(iconData:sub(s,s):byte());s=s+1dataLen=dataLen-3encode(t,3)endifdataLen==2thent=(iconData:sub(s,s):byte()<<16);s=s+1;t=t+(iconData:sub(s,s):byte()<<8);s=s+1;encode(t,2)elseifdataLen==1thent=(iconData:sub(s,s):byte()<<16);s=s+1;encode(t,1)endprint()
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1r...AAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

M2000 Interpreter

Using Urlmon.dll, UrlDownloadToFileW() function.

function global DownLoad$(filename$, drive$){Const BINDF_GETNEWESTVERSION = 0x10&if internet thenIf exist(filename$) then Try {dos "del "+quote$(dir$+filename$);} : Wait 200Declare 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 ifelse= "No Internet, Try Again"end if}iF Download$("rosettacode.ico","https://rosettacode.org/favicon.ico")="Ok" thena=buffer("rosettacode.ico")R$=string$(Eval$(a) as Encode64,0,0)clipboard R$report r$end if
Output:
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAA.................bnRsb2cvZmF2aWNvbnMvMjAxNS0wOC0wMi8xNDBkYmM4M2RmNWY3NmQyNmIzYWNlM2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==


Mathematica /Wolfram Language

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

Very interesting results.

Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm5ACgo6EAV1pYABcZGADO0c8AODs5AK2wrgBzdnQA6+7sAPz//QAAAwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA............................................................................AOaFhYbu7zPmhYWF5oaGhoaGhoaGhoaGhoaGhoaFhekA/////wAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Nim

importbase64importhttpclientvarclient=newHttpClient()letcontent=client.getContent("http://rosettacode.org/favicon.ico")letencoded=encode(content)ifencoded.len<=64:echoencodedelse:echoencoded[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>intmain(intargc,constchar*argv[]){@autoreleasepool{NSData*data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://rosettacode.org/favicon.ico"]];NSLog(@"%@",[database64Encoding]);}return0;}

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

(definebase64-codes"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")(definekernel(alist->ff(mapcons(iota(string-lengthbase64-codes))(string->bytesbase64-codes)))); returns n bits from input binary stream(define(bitsnhold)(letloop((holdhold))(vector-applyhold(lambda(vil)(cond; usual case((pair?l)(if(not(less?in))(values(>>v(-in))(vector(bandv(-(<<1(-in))1))(-in)l))(loop(vector(bor(<<v8)(carl))(+i8)(cdrl))))); special case - no more characters in input stream((null?l)(cond((=i0)(values#false#false)); done((<in)(values(<<v(-ni))(vector00#null)))(else(values(>>v(-in))(vector(bandv(-(<<1(-in))1))(-in)#null))))); just stream processing(else(loop(vectorvi(forcel))))))))); decoder.(define(encodestr)(case(mod(letloop((hold[00(str-iterstr)])(n0))(let*((bithold(bits6hold)))(whenbit(display(string(kernelbit))))(if(nothold)n(loophold(+n1)))))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:
SGVsbG8sIExpc3AhMDEyMzQ=VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

The rosettacode icon:

(defineicon(runes->string(bytevector->list(file->bytevector"favicon.ico"))))(encodeicon)
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCG...AABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Perl

#!perlusestrict;usewarnings;useMIME::Base64;open(my($fh),"<","favicon.ico")ordie;local$/;printencode_base64(<$fh>);
Output:

The first and last lines of output are:

AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Phix

For simplicity, the example from wp:

withjavascript_semanticsincludebuiltins\base64.estrings="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."stringe=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
withoutjsconstanturl="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})includelibcurl.eCURLcoderes=curl_easy_get_file(url,"",out)-- (no proxy)ifres!=CURLE_OKthenprintf(1,"Error %d downloading file\n",res)elsestringraw=get_text(out,GT_WHOLE_FILE+GT_BINARY)printf(1,"file %s saved (%,d bytes)\n",{out,length(raw)})stringb64=encode_base64(raw),chk=decode_base64(b64)printf(1,"base 64: %s, same: %t\n",{shorten(b64,"chars"),chk==raw})endif
Output:
attempting to download remote file https://rosettacode.org/favicon.ico to local file favicon.icofile 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

<?phpechobase64_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

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

Pluto

Library:Pluto-fmt

The standard library already contains Base 64 encode and decode functions.

localfmt=require"fmt"localbase64=require("base64")locals=io.contents("favicon.ico")print(fmt.abridge(base64.encode(s),40))
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAA...AQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

PowerShell

$webClient=[Net.WebClient]::new()$webClient.Headers.Add("User-Agent: Other")# so the server would not return error 403$bytes=$webClient.DownloadData('http://rosettacode.org/favicon.ico')$output=[Convert]::ToBase64String($bytes)$output
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

Here's a one-liner:

[Convert]::ToBase64String((iwrhttp://rosettacode.org/favicon.ico).Content)

PureBasic

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

Python

Python 2

importurllibimportbase64data=urllib.urlopen('http://rosettacode.org/favicon.ico').read()printbase64.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

importbase64# for b64encode()fromurllib.requestimporturlopenprint(base64.b64encode(urlopen('http://rosettacode.org/favicon.ico').read()))# Open the URL, retrieve the data and encode the data.

Racket

#langracket(requirenet/urlnet/base64)(base64-encode(call/input-url(string->url"http://rosettacode.org/favicon.ico")get-pure-portport->bytes))

Output:

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

Raku

(formerly Perl 6)

subMAIN {my$buf =slurp("./favicon.ico", :bin);saybuf-to-Base64($buf);}my@base64map =flat'A' ..'Z','a' ..'z', ^10,'+','/';subbuf-to-Base64($buf) {join'',gatherfor$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]printenbaseread/binaryhttps://rosettacode.org/favicon.ico
Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAg...AAABAAAAAQAAAAEAAAABAAAAAQAAAAE=

REXX

IncludeHow to use
IncludeSource code
The program uses a simple and straightforward string based method. Sufficient for the task, but inadequate for serious work.
Task 1 shows the Wikipedia examples. Task 2 converts the Rosetta Code icon.
The input favicon.ico was manually downloaded. The output favicon.dat is used in taskBase64 decode data.

--23Oct2025includeSettingsignaloffnotreadysay'BASE64 ENCODE DATA'sayversionsaycallTask1'Many hands make light work.'callTask1'Man'callTask1'Ma'callTask1'M'callTask1'any carnal pleasure.'callTask2exitTask1:procedureparseargxxsay'Original'xxsay'Encoded 'Encode64(xx)sayreturnTask2:procedurein='favicon.ico';out='favicon.dat'--Geticonfromweb(curlispre-installedonWindows10/11,UnixandMacOS)'curl https://rosettacode.org/favicon.ico --output'in'--ssl-no-revoke --silent'--Encoderr=Encode64(Charin(in,1,30000))callCharoutout,rr,1--Showheadandtailsay'Begin/end'in'encoded'doi=1by80to240saySubstr(rr,i,80)endsay'...'lc=Length(rr)doi=lc-239by80tolcsaySubstr(rr,i,80)endreturnEncode64:procedureparseargxx--Alphabeta='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'lx=Length(xx)--Convertcharactertobitsandappendsomezeroesxx=X2b(C2x(xx))00000;lb=Length(xx)-5;rr=''--Loopper6thrubitsdoi=1by6tolbb=Substr(xx,i,6)--Converttodecimald=X2d(B2x(b))+1--Getencodedcharactere=Substr(a,d,1)--Appendrr||=eend--Appendpaddingcharactersreturnrr||Copies('=',2*(lx//3=1)+(lx//3=2))includeAbend
Output:
BASE64 ENCODE DATAREXX-Regina_3.9.7(MT) 5.00 18 Mar 2025Original Many hands make light work.Encoded  TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsuOriginal ManEncoded  TWFuOriginal MaEncoded  TWE=Original MEncoded  TQ==Original any carnal pleasure.Encoded  YW55IGNhcm5hbCBwbGVhc3VyZS4=Begin/end favicon.ico encodedAAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAAADAAAABgAAAAAQAgAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwf8pAML/+gDC...AAAAAAAAAADB/ykAwv/6AML//wDC//8Awv/4AL//JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMH/kQDC//8Awv//AMH/hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPw/AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=

Ring

#=======================================##  Description : Base64 Sample#  Author      : Mansour Ayouni#=======================================## Loading RingQtload "guilib.ring"    # Creating a QByteArray objectoQByteArray = new QByteArray()# Adding a string to the QByteArray objectoQByteArray.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 objectoQByteArray = new QByteArray()oQByteArray.append("bXkgc3RyaW5n")? oQByteArray.fromBase64(oQByteArray).data()
Output:
bXkgc3RyaW5nmy string

RPL

Works with:RPL version HP-49C
« 3 OVER SIZE 3 MOD DUP 3 IFTE -    SWAP ""   1 PICK3 SIZEFOR 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 STWSSTR→BITS  ""   1 PICK3 SIZEFOR 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 +  6STEP   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'putsBase64.encode64open('http://rosettacode.org/favicon.ico'){|f|f.read}

Rust

Translation of:C++
usestd::fs::File;usestd::io::{self,Read,Write};// Import Write for stdoutusestd::path::Path;usestd::error::Error;// Base64 character setconstCHAR_SET:&'staticstr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";constPADDING_CHAR:char='=';/// Encodes a byte slice into a Base64 String.fnencode(input_bytes:&[u8])->String{// Calculate potential output size for pre-allocation.// Each 3 input bytes become 4 output chars. Add padding consideration.letoutput_len=((input_bytes.len()+2)/3)*4;letmutencoded=String::with_capacity(output_len);letchar_set_bytes=CHAR_SET.as_bytes();// Work with bytes for efficient indexing// Process input in chunks of 3 bytesforchunkininput_bytes.chunks(3){// Combine bytes into a 24-bit integer (u32)// byte1 << 16 | byte2 << 8 | byte3letmutcombined:u32=(chunk[0]asu32)<<16;ifchunk.len()>1{combined|=(chunk[1]asu32)<<8;}ifchunk.len()>2{combined|=chunk[2]asu32;}// Extract 4 6-bit indices from the 24-bit integerletidx1=(combined>>18)&63;letidx2=(combined>>12)&63;letidx3=(combined>>6)&63;letidx4=combined&63;// Append corresponding Base64 charactersencoded.push(char_set_bytes[idx1asusize]aschar);encoded.push(char_set_bytes[idx2asusize]aschar);// Handle padding for the last chunkifchunk.len()>1{encoded.push(char_set_bytes[idx3asusize]aschar);}else{encoded.push(PADDING_CHAR);// Pad 3rd char if only 1 input byte}ifchunk.len()>2{encoded.push(char_set_bytes[idx4asusize]aschar);}else{encoded.push(PADDING_CHAR);// Pad 4th char if 1 or 2 input bytes}}encoded}fnmain()->Result<(),Box<dynError>>{letfile_path="favicon.ico";// Hardcoded filename as in C++ example// --- File Reading ---// Open the fileletpath=Path::new(file_path);letmutfile=File::open(&path).map_err(|e|format!("Error opening file '{}': {}",file_path,e))?;// More context on error// Read the entire file into a vector of bytesletmutbuffer=Vec::new();file.read_to_end(&mutbuffer).map_err(|e|format!("Error reading file '{}': {}",file_path,e))?;// --- Encoding ---letencoded_string=encode(&buffer);// --- Output ---// Write the encoded string bytes to standard outputio::stdout().write_all(encoded_string.as_bytes())?;io::stdout().flush()?;// Ensure output is written immediatelyOk(())// Indicate success}

Scala

importjava.net.URLimportjava.util.Base64objectBase64SextendsApp{valconn=newURL("http://rosettacode.org/favicon.ico").openConnectionvalbytes=conn.getInputStream.readAllBytes()valresult=Base64.getEncoder.encodeToString(bytes)println(s"${result.take(22)} ...${result.drop(4830)}")assert(Base64.getDecoder.decode(result)sameElementsbytes)println(s"Successfully completed without errors. [total${compat.Platform.currentTime-executionStart} ms]")}

Seed7

The Seed7 libraryencoding.s7i definesthe functiontoBase64,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 base64put base64Encode ("To err is human, but to really foul things up you need a computer. --Paul R.Ehrlich")

Output:

VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=...VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuIC0tUGF1bCBSLkVocmxpY2g=

Sidef

vardata=%f'favicon.ico'.read(:raw)# binary stringprintdata.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:

funb64encfilename=letvalinstream=BinIO.openInfilenamevaldata=BinIO.inputAllinstreaminBase64.encodedatabeforeBinIO.closeIninstreamend
Output:
- b64enc "/tmp/favicon.ico";val it =  "AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNg#"  : string

Note the "#" means the output is truncated.

Tcl

Works with:Tcl version 8.6
packagerequireTcl8.6packagerequirehttpsettok[http::geturlhttp://rosettacode.org/favicon.ico]seticondata[http::data$tok]http::cleanup$tokputs[binaryencodebase64-maxlen64$icondata]

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

Library:Tcllib(Package: base64)
packagerequirebase64packagerequirehttpsettok[http::geturlhttp://rosettacode.org/favicon.ico]seticondata[http::data$tok]http::cleanup$tokputs[base64::encode-maxlen64$icondata]

VBA

OptionExplicitPublicFunctionDecode(sAsString)AsStringDimiAsInteger,jAsInteger,rAsByteDimFirstByteAsByte,SecndByteAsByte,ThirdByteAsByteDimSixBitArray()AsByte,ResultStringAsString,TokenAsStringDimCounterAsInteger,InputLengthAsIntegerInputLength=Len(s)ReDimSixBitArray(InputLength+1)j=1'j counts the tokens excluding cr, lf and paddingFori=1ToInputLength'loop over s and translate tokens to 0-63Token=Mid(s,i,1)SelectCaseTokenCase"A"To"Z"SixBitArray(j)=Asc(Token)-Asc("A")j=j+1Case"a"To"z"SixBitArray(j)=Asc(Token)-Asc("a")+26j=j+1Case"0"To"9"SixBitArray(j)=Asc(Token)-Asc("0")+52j=j+1Case"+"SixBitArray(j)=62j=j+1Case"/"SixBitArray(j)=63j=j+1Case"="'padding'CaseElse'cr and lfEndSelectNextir=(j-1)Mod4Counter=1Fori=1To(j-1)\4'loop over the six bit byte quadrupletsFirstByte=SixBitArray(Counter)*4+SixBitArray(Counter+1)\16SecndByte=(SixBitArray(Counter+1)Mod16)*16+SixBitArray(Counter+2)\4ThirdByte=(SixBitArray(Counter+2)Mod4)*64+SixBitArray(Counter+3)ResultString=ResultString&Chr(FirstByte)&Chr(SecndByte)&Chr(ThirdByte)Counter=Counter+4NextiSelectCaserCase3FirstByte=SixBitArray(Counter)*4+SixBitArray(Counter+1)\16SecndByte=(SixBitArray(Counter+1)Mod16)*16+SixBitArray(Counter+2)\4ResultString=ResultString&Chr(FirstByte)&Chr(SecndByte)Case2FirstByte=SixBitArray(Counter)*4+SixBitArray(Counter+1)\16ResultString=ResultString&Chr(FirstByte)EndSelectDecode=ResultStringEndFunctionPublicFunctionEncode(sAsString)AsStringDimInputLengthAsInteger,FirstByteAsByte,SecndByteAsByte,ThirdByteAsByte,rAsByteDimLineNumberAsInteger,zAsInteger,q()AsString,ResultStringAsStringDimFullLinesAsInteger,LastLineLengthAsInteger,CounterAsIntegerq=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=InputLengthMod3FullLines=((InputLength-r)/3)\20+1:LastLineLength=(InputLength-r)/3Mod20-1Counter=1ForLineNumber=1ToFullLinesForz=0ToIIf(LineNumber<FullLines,19,LastLineLength)'loop over the byte tripletsFirstByte=Asc(Mid(s,Counter,1))SecndByte=Asc(Mid(s,Counter+1,1))ThirdByte=Asc(Mid(s,Counter+2,1))Counter=Counter+3ResultString=ResultString&q(FirstByte\4)&q((FirstByteMod4)*16+_(SecndByte\16))&q((SecndByteMod16)*4+(ThirdByte\64))&q(ThirdByteMod64)NextzIfLineNumber<FullLinesThenResultString=ResultString&vbCrLfNextLineNumberSelectCaserCase2FirstByte=Asc(Mid(s,Counter,1))SecndByte=Asc(Mid(s,Counter+1,1))ResultString=ResultString&q(FirstByte\4)&q((FirstByteMod4)*16+_(SecndByte\16))&q((SecndByteMod16)*4)&"="Case1FirstByte=Asc(Mid(s,Counter,1))ResultString=ResultString&q(FirstByte\4)&q((FirstByteMod4)*16)&"=="EndSelectEncode=ResultStringEndFunctionPrivateFunctionReadWebFile(ByValvWebFileAsString)AsString'adapted from https://www.ozgrid.com/forum/forum/help-forums/excel-general/86714-vba-read-text-file-from-a-urlDimoXMLHTTPAsObject,iAsLong,vFFAsLong,oResp()AsByteSetoXMLHTTP=CreateObject("MSXML2.XMLHTTP")oXMLHTTP.Open"GET",vWebFile,FalseoXMLHTTP.sendDoWhileoXMLHTTP.readyState<>4:DoEvents:LoopoResp=oXMLHTTP.responseBody'Returns the results as a byte arrayReadWebFile=StrConv(oResp,vbUnicode)SetoXMLHTTP=NothingEndFunctionPublicSubTask()DimIn_AsString,OutAsString,bInAsStringDimfilelengthAsIntegerDimiAsIntegerIn_=ReadWebFile("http://rosettacode.org/favicon.ico")Out=Encode(In_)bIn=Decode(Out)Debug.Print"The first eighty and last eighty characters after encoding:"Debug.PrintLeft(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."EndSub
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)

importnet.httpimportencoding.base64importosfnmain(){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 savedecoded:=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"forFile,Stdoutimport"./fmt"forConv,Fmtimport"./seq"forLstvaralpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"varencode=Fn.new{|s|varc=s.countif(c==0)returnsvare=""for(bins)e=e+Fmt.swrite("$08b",b)if(c==2){e=e+"00"}elseif(c==1){e=e+"0000"}vari=0while(i<e.count){varix=Conv.atoi(e[i..i+5],2)System.write(alpha[ix])i=i+6}if(c==2){System.write("=")}elseif(c==1){System.write("==")}Stdout.flush()}vars=File.read("favicon.ico").bytes.toListfor(chunkinLst.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 whenattempting to read beyond the end. The first attempt to read beyond theend returns an EOF code ($1A -- useful when reading text files). Thesecond attempt to read beyond the end causes an error, which by defaultaborts a program. However, error trapping is turned off here [withTrap(false)] and GetErr is used to detect the error, and thus theend-of-file.

The output here is different than other examples because the icon at theprovided 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 insteadFD:= FOpen("favicon.ico", 0);   \open input fileFSet(FD, ^I);OpenI(3);FD:= FOpen("favicon.txt", 1);   \open file for outputFSet(FD, ^O);OpenO(3);Char:= ChIn(3);                 \initialize one-char look-aheadColumn:= 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 headerb64:=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: TrueData(4,920)AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm...AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
Retrieved from "https://rosettacode.org/wiki/Base64_encode_data?oldid=390244"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2026 Movatter.jp