Java Base64 Encode base64encode(String str)

Here you can find the source of base64encode(String str)

Description

baseencode

License

Open Source License

Declaration

public static String base64encode(String str) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

public class Main {
    static String base64alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";

    public static String base64encode(String str) {
        byte[] utf8;
        try {//from  ww w. ja  v a  2 s  .  c  o  m
            utf8 = str.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new InternalError(ex.toString());
        }
        StringBuffer sb = new StringBuffer((utf8.length + 2) / 3 * 4);
        int i;
        int len = utf8.length;
        for (i = 0; i < len - 2; i += 3) {
            int value = (utf8[i] & 0xff) << 16 | (utf8[i + 1] & 0xff) << 8
                    | (utf8[i + 2] & 0xff);
            sb.append(base64alphabet.charAt(value >> 18))
                    .append(base64alphabet.charAt((value >> 12) & 0x3f))
                    .append(base64alphabet.charAt((value >> 6) & 0x3f))
                    .append(base64alphabet.charAt(value & 0x3f));
        }
        if (i < len) {
            int value = utf8[i++] & 0xff;
            sb.append(base64alphabet.charAt(value >> 2));
            if (i < len) {
                value = (value << 8) + (utf8[i++] & 0xff);
                sb.append(base64alphabet.charAt((value >> 4) & 0x3f));
                sb.append(base64alphabet.charAt((value << 2) & 0x3f));
            } else {
                sb.append(base64alphabet.charAt((value << 4) & 0x3f));
                sb.append('=');
            }
            sb.append('=');
        }
        return sb.toString();
    }
}

Related

  1. base64Encode(String plainTextString)
  2. base64Encode(String s)
  3. base64encode(String s)
  4. base64Encode(String s)
  5. base64Encode(String s)
  6. base64Encode(String string)
  7. base64Encode(String string)
  8. base64encode(String text)
  9. base64EncodeGeneric(String digits, byte[] data)