Base64 encode data: Difference between revisions

added RPL
(→‎{{header|Frink}}: Reformatted base-64 output)
(added RPL)
 
(11 intermediate revisions by 9 users not shown)
Line 373:
</syntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<syntaxhighlight lang="bacon">CONST file$ = "favicon.ico"
binary = BLOAD(file$)
Line 902 ⟶ 903:
M2ZlYTViYzI5ZS5pY28ucG5nBect2gAAAABJRU5ErkJggg==
</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSlog.incl"
 
local fn EncodeStringAsBase64( stringToEncode as CFStringRef ) as CFStringRef
CFStringRef encodedBase64Str = NULL
CFDataRef dataToEncode = fn StringData( stringToEncode, NSUTF8StringEncoding )
encodedBase64Str = fn DataBase64EncodedString( dataToEncode, 0 )
end fn = encodedBase64Str
 
 
local fn DecodeBase64String( base64String as CFStringRef ) as CFStringRef
CFStringRef decodedString = NULL
CFDataRef encodedData = fn DataWithBase64EncodedString( base64String, NSDataBase64DecodingIgnoreUnknownCharacters )
decodedString = fn StringWithData( encodedData, NSUTF8StringEncoding )
end fn = decodedString
 
 
CFStringRef originalString, encodedBase64String, decodedBase64String
 
originalString = @"This is a test string to be encoded as Base64 and then decoded."
NSLog( @"This is the original string:\n\t%@\n", originalString )
 
encodedBase64String = fn EncodeStringAsBase64( originalString )
NSLog( @"This is the original string encoded as Base84:\n\t%@\n", encodedBase64String )
 
decodedBase64String = fn DecodeBase64String( encodedBase64String )
NSLog( @"This is the Base64 string decoded:\n\t%@", decodedBase64String )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
This is the original string:
This is a test string to be encoded as Base64 and then decoded.
 
This is the original string encoded as Base84:
VGhpcyBpcyBhIHRlc3Qgc3RyaW5nIHRvIGJlIGVuY29kZWQgYXMgQmFzZTY0IGFuZCB0aGVuIGRlY29kZWQu
 
This is the Base64 string decoded:
This is a test string to be encoded as Base64 and then decoded.
</pre>
 
 
 
=={{header|Go}}==
Line 1,131 ⟶ 1,178:
 
=={{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
 
Line 1,205 ⟶ 1,290:
}
}</syntaxhighlight>
<pre>AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=</pre>
 
=== Java 8 version ===
<syntaxhighlight lang="java">import java.nio.file.*;
import java.util.Base64;
 
public class Base64Task {
 
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Paths.get("favicon.ico"));
String result = Base64.getEncoder().encodeToString(bytes);
System.out.println(result);
}
}</syntaxhighlight>
 
<pre>AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=</pre>
 
Line 1,433 ⟶ 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}}==
Line 1,728 ⟶ 1,836:
 
=={{header|Python}}==
===Python 2===
<syntaxhighlight lang="python">import urllib
import base64
Line 1,734 ⟶ 1,843:
print base64.b64encode(data)</syntaxhighlight>
(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}}==
Line 1,891 ⟶ 2,007:
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>
 
Line 2,007 ⟶ 2,152:
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAWJQTFRFAAAA/8IA/8EA/8IA/8IA/8IA/8IA/8IA/8IA/8I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QAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNS0wOC0wMlQyMDozOToxMCswMDowMIafoa0AAABGdEVYdHNvZnR3YXJlAEltYWdlTWFnaWNrIDYuNy44LTkgMjAxNC0wNS0xMiBRMTYgaHR0cDovL3d3dy5pbWFnZW1hZ2ljay5vcmfchu0AAAAAGHRFWHRUaHVtYjo6RG9jdW1lbnQ6OlBhZ2VzADGn/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}}==
Line 2,145 ⟶ 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 2,150 ⟶ 2,332:
{{libheader|Wren-seq}}
From first principles using string manipulation. Quick enough here.
<syntaxhighlight lang="ecmascriptwren">import "io" for File, Stdout
import "./fmt" for Conv, Fmt
import "./seq" for Lst
 
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Line 2,189 ⟶ 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>
 
1,150

edits