]> Creatis software - CreaPhase.git/blob - octave_packages/strings-1.1.0/base64encode.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / strings-1.1.0 / base64encode.m
1 ## Author: Paul Kienzle <pkienzle@users.sf.net>
2 ## This program is granted to the public domain.
3
4 ## -*- texinfo -*-
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.
11 ## 
12 ## Example:
13 ## @example
14 ## @group
15 ## base64encode('Hakuna Matata',true) 
16 ## ##returns 'SGFrdW5hIE1hdGF0YQ=='
17 ##
18 ## @end group
19 ## @end example
20 ## @seealso{base64decode}
21 ## @end deftypefn
22
23 function Y = base64encode (X, do_reshape)
24
25   if (nargin < 1)
26     print_usage;
27   elseif nargin != 2
28     do_reshape=false;
29   endif
30   if (ischar(X))
31     X = toascii(X);
32   elseif (any(X(:)) != fix(X(:)) || any(X(:) < 0) || any(X(:) > 255))
33     error("base64encode is expecting integers in the range 0 .. 255");
34   endif
35
36   n = length(X(:));
37   X = X(:);
38
39   ## split the input into three pieces, zero padding to the same length
40   in1 = X(1:3:n);
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);
45
46   ## put the top bits of the inputs into the bottom bits of the 
47   ## corresponding outputs
48   out1 = fix(in1/4);
49   out2 = fix(in2/16);
50   out3 = fix(in3/64);
51
52   ## add the bottom bits of the inputs as the top bits of the corresponding
53   ## outputs
54   out4 =            in3 - 64*out3;
55   out3 = out3 +  4*(in2 - 16*out2);
56   out2 = out2 + 16*(in1 -  4*out1);
57
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
61
62   ## 6-bit encoding table, plus 1 for padding
63   table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
64
65   table([ out1']+ 1);
66   table([ out2']+ 1);
67   table([ out3']+ 1);
68   table([ out4']+ 1);
69
70   Y = table([ out1'; out2'; out3'; out4' ] + 1);
71
72   if ( do_reshape )
73      Y = reshape(Y,[1, prod(size(Y))]);
74   end
75 endfunction
76
77 %!assert(base64encode('Hakuna Matata',true),'SGFrdW5hIE1hdGF0YQ==')