home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / gostools.zip / b64en.cmd next >
OS/2 REXX Batch file  |  1995-06-14  |  2KB  |  75 lines

  1. /* BASE 64 encoding   */
  2. /* By Michael Warmuth */
  3.  
  4. /* Get arguments <input_string> */
  5. parse arg g.in_str
  6.  
  7. /* Set global vars */
  8. g.b64_table = xrange('A','Z')xrange('a','z')xrange('0','9')'+/='
  9. g.col = 0
  10. g.chr = 0
  11. g.len = length(g.in_str)
  12. g.out_str = ''
  13.  
  14. /* Do with all chars of input file */
  15. do until char=-1
  16.    sum = 0                                   /* Sum of next three chars */
  17.    no = 4                                    /* Number of chars to write */
  18.    do i=1 to 3
  19.       char = next_chr()                      /* Get next char */
  20.       if char=-1 then do                     /* End of file: leave */
  21.          no = ((i - 1) * 8) % 6              /* Correct number of chars to write */
  22.          if (((i - 1) * 8) // 6)\=0 then no = no + 1
  23.          do 4-i
  24.             sum = sum * 256
  25.          end /* do */
  26.          leave                               /* leave loop */
  27.       end  /* Do */
  28.       else sum = sum * 256 + c2d(char)       /* Calculate sum of chars */
  29.    end /* do */
  30.  
  31.    do i=1 to 4                               /* Produce chars to write out */
  32.       out.i = sum // 64
  33.       sum = sum % 64
  34.    end /* do */
  35.    if no\=0 then do
  36.       do i=1 to (4-no)
  37.          out.i = 64                          /* Fill with '=' at end of file */
  38.       end /* do */
  39.       do i=4 to 1 by -1
  40.          call writeb64 out.i
  41.       end /* do */
  42.    end  /* Do */
  43. end /* do */
  44.  
  45. exit g.out_str
  46.  
  47.  
  48.  
  49. /* Get next char */
  50. next_chr: procedure expose g.
  51.  
  52. g.chr = g.chr + 1
  53. if g.chr>g.len then retc = -1
  54. else retc = substr(g.in_str,g.chr,1)
  55.  
  56. return retc
  57.  
  58.  
  59.  
  60. /* Write out one char */
  61. writeb64: procedure expose g.
  62.  
  63. parse arg chrno
  64.  
  65. /* Write char */
  66. g.out_str = g.out_str || substr(g.b64_table,chrno+1,1)
  67.  
  68. g.col = g.col + 1                            /* Increment column counter */
  69. if g.col=76 then do                          /* Width reached: new line */
  70.    g.out_str = g.out_str || '0d0a'x
  71.    g.col = 0
  72. end  /* Do */
  73.  
  74. return
  75.