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