Android 标准的Base64编码和解码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Android 标准的Base64编码和解码
2011-09-26 03:39
import java.io.IOException;
public class Base64 {
/** prevents anyone from instantiating this class */
private Base64() {
}
/**
* This character array provides the alphabet map from RFC1521. */
private final static char ALPHABET[] = {
// 0 1 2 3 4 5 6 7
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5
'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6
'4', '5', '6', '7', '8', '9', '+', '/' // 7
};
/**
* Decodes a 7 bit Base64 character into its binary value.
*/
private static int valueDecoding[] = new int[128];
/**
* initializes the value decoding array from the
* character map
*/
static {
for (int i = 0; i < valueDecoding.length; i++) {
valueDecoding[i] = -1;
}
for (int i = 0; i < ALPHABET.length; i++) {
valueDecoding[ALPHABET[i]] = i;
}
}
/**
* Converts a byte array into a Base64 encoded string.
* @param data bytes to encode
* @param offset which byte to start at
* @param length how many bytes to encode; padding will be added if needed
* @return base64 encoding of data; 4 chars for every 3 bytes
*/
public static String encode(byte[] data, int offset, int length) { int i;
int encodedLen;
char[] encoded;
// 4 chars for 3 bytes, run input up to a multiple of 3
encodedLen = (length + 2) / 3 * 4;
encoded = new char [encodedLen];
for (i = 0, encodedLen = 0; encodedLen < encoded.length;
i += 3, encodedLen += 4) {
encodeQuantum(data, offset + i, length - i, encoded, encodedLen);
}
return new String(encoded);
}
/**
* Encodes 1, 2, or 3 bytes of data as 4 Base64 chars.
*
* @param in buffer of bytes to encode
* @param inOffset where the first byte to encode is
* @param len how many bytes to encode
* @param out buffer to put the output in
* @param outOffset where in the output buffer to put the chars */
private static void encodeQuantum(byte in[], int inOffset, int len, char out[], int outOffset) {
byte a = 0, b = 0, c = 0;
a = in[inOffset];
out[outOffset] = ALPHABET[(a >>> 2) & 0x3F];
if (len > 2) {
b = in[inOffset + 1];