Build your own Base64 Encode - Android android.util

Android examples for android.util:Base64

Description

Build your own Base64 Encode

Demo Code


public class Main {

  public static String base64Encode(String string) {
    // base64 encode char array
    char _base64EncodeChars[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
        'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
        '9', '+', '/' };

    // check string
    if (null != string) {
      // get string bytes data
      byte[] _bytesData = string.getBytes();

      // define return string builder
      StringBuilder _ret = new StringBuilder();

      // define index, byte1, byte2, byte3 and init index
      int i = 0;/*  w  w w .  ja  va  2  s.  co  m*/
      int b1, b2, b3;

      while (i < _bytesData.length) {
        b1 = _bytesData[i++] & 0xff;
        if (i == _bytesData.length) {
          _ret.append(_base64EncodeChars[b1 >>> 2]);
          _ret.append(_base64EncodeChars[(b1 & 0x3) << 4]);
          _ret.append("==");
          break;
        }
        b2 = _bytesData[i++] & 0xff;
        if (i == _bytesData.length) {
          _ret.append(_base64EncodeChars[b1 >>> 2]);
          _ret.append(_base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
          _ret.append(_base64EncodeChars[(b2 & 0x0f) << 2]);
          _ret.append("=");
          break;
        }
        b3 = _bytesData[i++] & 0xff;
        _ret.append(_base64EncodeChars[b1 >>> 2]);
        _ret.append(_base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
        _ret.append(_base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
        _ret.append(_base64EncodeChars[b3 & 0x3f]);
      }

      return _ret.toString();
    } else {
      return null;
    }
  }

}

Related Tutorials