File: base64encode.m

package info (click to toggle)
octave-strings 1.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 452 kB
  • ctags: 29
  • sloc: makefile: 79; cpp: 67; sh: 25
file content (77 lines) | stat: -rw-r--r-- 2,212 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
## -*- texinfo -*-
## @deftypefn @var{Y} = {Function File} {} base64encode(@var{X})
## @deftypefnx @var{Y} = {Function File} {} base64encode(@var{X}, @var{do_reshape})
## Convert X into string of printable characters according to RFC 2045.
## The input may be a string or a matrix of integers in the range 0..255.
## If want the output in the 1-row of strings format, pass the 
## @var{do_reshape} argument as true.
## 
## Example:
## @example
## base64encode('Hakuna Matata',true) 
## ##returns 'SGFrdW5hIE1hdGF0YQ=='
##
## @end example
## @end deftypefn
## @seealso{base64decode}
##

## This program is in the public domain
## Author: Paul Kienzle <pkienzle@users.sf.net>
##
function Y = base64encode(X,do_reshape)

  if (nargin < 1)
    usage("Y = base64encode(X,[do_reshape])");
  elseif nargin != 2
    do_reshape=false;
  endif
  if (ischar(X))
    X = toascii(X);
  elseif (any(X(:)) != fix(X(:)) || any(X(:) < 0) || any(X(:) > 255))
    error("base64encode is expecting integers in the range 0 .. 255");
  endif

  n = length(X(:));
  X = X(:);

  ## split the input into three pieces, zero padding to the same length
  in1 = X(1:3:n);
  in2 = zeros(size(in1));
  in3 = zeros(size(in1));
  in2(1:length(2:3:n)) = X(2:3:n);
  in3(1:length(3:3:n)) = X(3:3:n);

  ## put the top bits of the inputs into the bottom bits of the 
  ## corresponding outputs
  out1 = fix(in1/4);
  out2 = fix(in2/16);
  out3 = fix(in3/64);

  ## add the bottom bits of the inputs as the top bits of the corresponding
  ## outputs
  out4 =            in3 - 64*out3;
  out3 = out3 +  4*(in2 - 16*out2);
  out2 = out2 + 16*(in1 -  4*out1);

  ## correct the output for padding
  if (length(2:3:n) < length(1:3:n)) out3(length(out3)) = 64; endif
  if (length(3:3:n) < length(1:3:n)) out4(length(out4)) = 64; endif

  ## 6-bit encoding table, plus 1 for padding
  table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  table([ out1']+ 1);
  table([ out2']+ 1);
  table([ out3']+ 1);
  table([ out4']+ 1);

  Y = table([ out1'; out2'; out3'; out4' ] + 1);

  if ( do_reshape )
     Y = reshape(Y,[1, prod(size(Y))]);
  end
endfunction
%!
%!assert(base64encode('Hakuna Matata',true),'SGFrdW5hIE1hdGF0YQ==')
%!