Base64 encode data: Difference between revisions
(Added zkl) |
|||
Line 441: | Line 441: | ||
puts [base64::encode -maxlen 64 $icondata]</lang> |
puts [base64::encode -maxlen 64 $icondata]</lang> |
||
=={{header|zkl}}== |
|||
Using shared libraries for cURL and message hashing: |
|||
<lang zkl>var MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl"); |
|||
icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0) |
|||
icon=icon[0][icon[1],*]; // remove header |
|||
b64:=MsgHash.base64encode(icon); |
|||
b64.println(); |
|||
b64.text.println();</lang> |
|||
{{out}} |
|||
Encoded to 72 characters per line |
|||
<pre> |
|||
Data(4,920) |
|||
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA |
|||
AAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm |
|||
... |
|||
AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAAB |
|||
AAAAAQAAAAEAAAABAAAAAQAAAAE= |
|||
</pre> |
Revision as of 19:10, 3 August 2014
Convert an array of bytes or binary string to the base64-encoding of that string and output that value. Use the icon for Rosetta Code as the data to convert.
C
libresolv
(libresolv is included on most Unix-like systems)
<lang c>#include <stdio.h>
- include <stdlib.h>
- include <resolv.h>
- include <fcntl.h>
- include <unistd.h>
- include <sys/types.h>
- include <sys/stat.h>
- include <sys/mman.h>
int main() {
int fin = open("favicon.ico", O_RDONLY); if (fin == -1) return 1;
struct stat st; if (fstat(fin, &st)) return 1;
void *bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin, 0); if (bi == MAP_FAILED) return 1;
int outLength = ((st.st_size + 2) / 3) * 4 + 1; char *outBuffer = malloc(outLength); if (outBuffer == NULL) return 1;
int encodedLength = b64_ntop(bi, st.st_size, outBuffer, outLength); if (encodedLength < 0) return 1;
puts(outBuffer);
free(outBuffer); munmap(bi, st.st_size); close(fin);
return 0;
}</lang> Compile with
gcc -lresolv -o base64encode base64encode.c
Manual implementation
The following reads standard input and writes base64-encoded stream to standard output, e.g. ./a.out <some_random_file >/dev/null if you don't want to see the output. It gives identical output as the common base64 utility program, though much less efficiently. <lang c>#include <stdio.h>
- include <unistd.h>
typedef unsigned long UL;
int main(void) { const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; unsigned char c[4]; UL u, len, w = 0;
do { c[1] = c[2] = 0;
if (!(len = read(fileno(stdin), c, 3))) break; u = (UL)c[0]<<16 | (UL)c[1]<<8 | (UL)c[2];
putchar(alpha[u>>18]); putchar(alpha[u>>12 & 63]); putchar(len < 2 ? '=' : alpha[u>>6 & 63]); putchar(len < 3 ? '=' : alpha[u & 63]);
if (++w == 19) w = 0, putchar('\n'); } while (len == 3);
if (w) putchar('\n');
return 0; }</lang>
D
<lang d>void main() {
import std.stdio, std.base64, std.net.curl, std.string;
const f = "http://rosettacode.org/favicon.ico".get.representation; Base64.encode(f).writeln;
}</lang>
- Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAwqgIAADCjgUAACgAAAAQAAAAIAA... AAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQ==
Delphi
<lang delphi>program Base64EncodeData; {$APPTYPE CONSOLE} uses IdHTTP, IdCoderMIME;
var
lSrcString: string; lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create(nil); try lSrcString := lHTTP.Get('http://rosettacode.org/favicon.ico'); Writeln(TIdEncoderMIME.EncodeString(lSrcString)); finally lHTTP.Free; end;
end.</lang>
Erlang
<lang 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).</lang>
- Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4F...AAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
Go
<lang Go>package main
import (
"encoding/base64" "fmt" "io/ioutil" "net/http"
)
func main() {
r, err := http.Get("http://rosettacode.org/favicon.ico") if err != nil { fmt.Println(err) return } defer r.Body.Close() d, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Println(err) return } fmt.Println(base64.StdEncoding.EncodeToString(d))
}</lang>
J
Solution (standard library):<lang j> load'convert/misc' NB. use 'tobase64'</lang> Solution (handrolled):<lang j> tobase64 =: padB64~ b2B64
padB64 =: , '=' #~ 0 2 1 i. 3 | # b2B64 =: BASE64 {~ _6 #.\ (8#2) ,@:#: a.&i.</lang>
Example:<lang j> load'web/gethttp'
76 {. tobase64 gethttp 'http://rosettacode.org/favicon.ico'
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA</lang>
JavaScript
<lang JavaScript>(function(){//ECMAScript doesn't have an internal base64 function or method, so we have to do it ourselves, isn't that exciting?
function stringToArrayUnicode(str){for(var i=0,l=str.length,n=[];i<l;i++)n.push(str.charCodeAt(i));return n;} function generateOnesByLength(n){//Attempts to generate a binary number full of ones given a length.. they don't redefine each other that much. var x=0; for(var i=0;i<n;i++){ x<<=1;x|=1;//I don't know if this is performant faster than Math.pow but seriously I don't think I'll need Math.pow, do I? } return x; } function paf(_offset,_offsetlength,_number){//I don't have any name for this function at ALL, but I will explain what it does, it takes an offset, a number and returns the base64 number and the offset of the next number. //the next function will be used to extract the offset of the number.. var a=6-_offsetlength,b=8-a;//Oh god, 8 is HARDCODED! Because 8 is the number of bits in a byte!!! //And 6 is the mini-byte used by wikipedia base64 article... at least on 2013. //I imagine this code being read in 2432 or something, that probably won't happen.. return [_number&generateOnesByLength(b),b,(_offset<<a)|(_number>>b)];//offset & offsetlength & number } function toBase64(uint8array){//of bits, each value may not have more than 255 bits... //a normal "array" should work fine too.. //From 0x29 to 0x5a plus from 0x61 to 0x7A AND from 0x30 to 0x39 //Will not report errors if an array index has a value bigger than 255.. it will likely fail. var a=[],i,output=[]; for(i=0x41;i<=0x5a;i++){//A-Z a.push(String.fromCharCode(i)); } for(i=0x61;i<=0x7A;i++){//a-z a.push(String.fromCharCode(i)); } for(i=0x30;i<=0x39;i++){//0-9 a.push(String.fromCharCode(i)); } a.push('+','/'); var offset=0,offsetLength=0,x; for(var i=0,l=uint8array.length;i<l;i++){ if(offsetLength==6){//if offsetlength is 6 that means that a whole offset is occupying the space of a byte, can you believe it. offsetLength=0; output.push(a[offset]); offset=0; i--; continue; } x=paf(offset,offsetLength,uint8array[i]); offset=x[0]; offsetLength=x[1]; output.push(a[x[2]]); } if(offsetLength){ if(offsetLength==6){ output.push(a[offset]); }else{ var y=(6-offsetLength)/2; x=paf(offset,offsetLength,0); offset=x[0]; output.push(a[x[2]]); switch (y){ case 2:output.push('=');//This thingy right here, you know.. the offsets also, no break statement; case 1:output.push('=');break; } } } return output.join();//You can change it so the result is an array instead!!!! }
//Usage
return toBase64(stringToArrayUnicode("Nothing seems hard to the people who don't know what they're talking about."))
}())</lang>
Using btoa (HTML5)
Works with IE10 or higher.
HTML5 saves the day! introducing two methods to the DOM!
These are btoa and atob, see spec
<lang JavaScript>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</lang>To make it.. just work, you could convert it to UTF-8 Manually or..
JSON.stringify it or..
encodeURIComponent it.
Using Node.js
<lang JavaScript>var http = require('http'); var options = {
host: 'rosettacode.org', path: '/favicon.ico'
}; callback = function(response) {
var str = ; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(new Buffer(str).toString('base64'));//Base64 encoding right here. });
} </lang>
Lasso
<lang 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</lang>
Objective-C
<lang objc>#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool { NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://rosettacode.org/favicon.ico"]]; NSLog(@"%@", [data base64Encoding]); } return 0;
}</lang>
Perl
<lang perl>#!perl use strict; use warnings; use MIME::Base64; open(my($fh), "<", "favicon.ico") or die; local $/; print encode_base64(<$fh>); </lang>
- Output:
The first and last lines of output are:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgAAAAA
AAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAE=
Perl 6
<lang perl6>sub MAIN {
my $buf = slurp("/tmp/favicon.ico", :bin); say buf-to-Base64($buf);
}
my @base64map = 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';
sub buf-to-Base64($buf) {
join , gather for $buf.list -> $a, $b = [], $c = [] { my $triplet = ($a +< 16) +| ($b +< 8) +| $c; take @base64map[($triplet +> (6 * 3)) +& 0x3F]; take @base64map[($triplet +> (6 * 2)) +& 0x3F]; if $c.elems { take @base64map[($triplet +> (6 * 1)) +& 0x3F]; take @base64map[($triplet +> (6 * 0)) +& 0x3F]; } elsif $b.elems { take @base64map[($triplet +> (6 * 1)) +& 0x3F]; take '='; } else { take '==' } }
}</lang>
- Output:
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAA...QAAAAEAAAABAAAAAQAAAAE=
PHP
<lang php><?php echo base64_encode(file_get_contents("http://rosettacode.org/favicon.ico"));/*1 liner*/ ?></lang>
Python
<lang python>import urllib import base64
data = urllib.urlopen('http://rosettacode.org/favicon.ico').read() print base64.b64encode(data)</lang> (For me this gets the wrong data; the data is actually an error message. But still, it base-64 encodes it.)
Racket
<lang 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))
</lang> Output: <lang racket>
- "AAABAAIAEBAAAAAAAABoBQAA...AQAAAAE=\r\n"
</lang>
REXX
<lang rexx>/*REXX program converts text (from a file or CL) to a base64 text string*/ parse arg iFID @ /*get optional arguments. */ if iFID== then iFID='favicon.ico' /*use the default input file. */ chunk=10000 /*amount of bytes to read a file.*/ if @= then /* [↓] read the input file ──►@ */
do s=1 by chunk until y==; y=charin(iFID,s,chunk); @=@||y; end
t=base64(@) say center(' input', 79, '─'); say @ /*show header & the input text.*/ say center('base64', 79, '─'); say t /* " " " " base64 " */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BASE64 subroutine───────────────────*/ base64: procedure; parse arg x; $= /*get the input string, nullify $*/ z='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
do i=0 for 64; !.i=substr(z,i+1,1); end /*assign base64 array*/
L=length(x)*8 /*save length of b for later.*/ b=x2b(c2x(x))0000000000000000 /*X──►binary, add some 0 padding.*/
do j=1 by 6 to L /*traipse through the bit string.*/ _=x2d( b2x( substr(b, j, 6) )) /*compute index into BASE64 table*/ $=$ || !._ /*append this to $ (the output).*/ end /*j*/
return $||copies('=', 2*(L//6==2)+(L//6==4)) /*maybe append equal signs*/</lang>
For the various outputs, serveral input texts from the Wikipedia article on Base64 [1] were used to demonstrate how padding works.
output when using the input of: , any carnal pleasure.
──────────────────────────────────── input───────────────────────────────────── any carnal pleasure. ────────────────────────────────────base64───────────────────────────────────── YW55IGNhcm5hbCBwbGVhc3VyZS4=
output when using the input of: , any carnal pleasure
──────────────────────────────────── input───────────────────────────────────── any carnal pleasure ────────────────────────────────────base64───────────────────────────────────── YW55IGNhcm5hbCBwbGVhc3VyZQ==
output when using the input of: , any carnal pleasur
──────────────────────────────────── input───────────────────────────────────── any carnal pleasur ────────────────────────────────────base64───────────────────────────────────── YW55IGNhcm5hbCBwbGVhc3Vy
output when using the input of: , any carnal pleasu
──────────────────────────────────── input───────────────────────────────────── any carnal pleasu ────────────────────────────────────base64───────────────────────────────────── YW55IGNhcm5hbCBwbGVhc3U=
output when using the input of: , any carnal pleas
──────────────────────────────────── input───────────────────────────────────── any carnal pleas ────────────────────────────────────base64───────────────────────────────────── YW55IGNhcm5hbCBwbGVhcw==
Ruby
<lang ruby>require 'open-uri' require 'base64'
puts Base64.encode64 open('http://rosettacode.org/favicon.ico') {|f| f.read}</lang>
Seed7
<lang seed7>$ 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;</lang>
Tcl
<lang tcl>package require Tcl 8.6 package require http
set tok [http::geturl http://rosettacode.org/favicon.ico] set icondata [http::data $tok] http::cleanup $tok
puts [binary encode base64 -maxlen 64 $icondata]</lang> With older versions of Tcl, the base64 encoding is best supported via an external package:
<lang tcl>package require base64 package require http
set tok [http::geturl http://rosettacode.org/favicon.ico] set icondata [http::data $tok] http::cleanup $tok
puts [base64::encode -maxlen 64 $icondata]</lang>
zkl
Using shared libraries for cURL and message hashing: <lang zkl>var MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl");
icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0) icon=icon[0][icon[1],*]; // remove header b64:=MsgHash.base64encode(icon); b64.println(); b64.text.println();</lang>
- Output:
Encoded to 72 characters per line
Data(4,920) AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAABAAgA AAAAAEABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wCGiYcARkhHAL/CwAAmKScAam1rAOPm ... AAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAQAAAAEAAAAB AAAAAQAAAAEAAAABAAAAAQAAAAE=