1 ## Author: Paul Kienzle <pkienzle@users.sf.net>
2 ## This program is granted to the public domain.
5 ## @deftypefn {Function File} {@var{Y} =} base64encode (@var{X})
6 ## @deftypefnx {Function File} {@var{Y} =} base64encode (@var{X}, @var{do_reshape})
7 ## Convert X into string of printable characters according to RFC 2045.
8 ## The input may be a string or a matrix of integers in the range 0..255.
9 ## If want the output in the 1-row of strings format, pass the
10 ## @var{do_reshape} argument as true.
15 ## base64encode('Hakuna Matata',true)
16 ## ##returns 'SGFrdW5hIE1hdGF0YQ=='
20 ## @seealso{base64decode}
23 function Y = base64encode (X, do_reshape)
32 elseif (any(X(:)) != fix(X(:)) || any(X(:) < 0) || any(X(:) > 255))
33 error("base64encode is expecting integers in the range 0 .. 255");
39 ## split the input into three pieces, zero padding to the same length
41 in2 = zeros(size(in1));
42 in3 = zeros(size(in1));
43 in2(1:length(2:3:n)) = X(2:3:n);
44 in3(1:length(3:3:n)) = X(3:3:n);
46 ## put the top bits of the inputs into the bottom bits of the
47 ## corresponding outputs
52 ## add the bottom bits of the inputs as the top bits of the corresponding
55 out3 = out3 + 4*(in2 - 16*out2);
56 out2 = out2 + 16*(in1 - 4*out1);
58 ## correct the output for padding
59 if (length(2:3:n) < length(1:3:n)) out3(length(out3)) = 64; endif
60 if (length(3:3:n) < length(1:3:n)) out4(length(out4)) = 64; endif
62 ## 6-bit encoding table, plus 1 for padding
63 table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
70 Y = table([ out1'; out2'; out3'; out4' ] + 1);
73 Y = reshape(Y,[1, prod(size(Y))]);
77 %!assert(base64encode('Hakuna Matata',true),'SGFrdW5hIE1hdGF0YQ==')