Base64 將任意二進位資料編碼為 64 個可列印字元(A-Z、a-z、0-9、+、/),常用於 HTTP Basic Auth、Email 附件、XML/JSON 嵌入二進位。J2ME 無內建 Base64,需自行實作或引入輕量庫。
= 補齊。= 提前結束。HBase64package hlib;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
public class HBase64 {
private static final char[] MAP =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
// ========== 編碼 ==========
public static String encode(byte[] data) {
StringBuffer buf = new StringBuffer((data.length + 2) / 3 * 4);
int i = 0, len = data.length;
while (i <= len - 3) {
int d = ((data[i] & 0xFF) << 16) | ((data[i+1] & 0xFF) << 8) | (data[i+2] & 0xFF);
buf.append(MAP[(d >>> 18) & 0x3F]);
buf.append(MAP[(d >>> 12) & 0x3F]);
buf.append(MAP[(d >>> 6) & 0x3F]);
buf.append(MAP[d & 0x3F]);
i += 3;
}
if (i == len - 2) { // 剩 2 bytes
int d = ((data[i] & 0xFF) << 16) | ((data[i+1] & 0xFF) << 8);
buf.append(MAP[(d >>> 18) & 0x3F]);
buf.append(MAP[(d >>> 12) & 0x3F]);
buf.append(MAP[(d >>> 6) & 0x3F]);
buf.append('=');
} else if (i == len - 1) { // 剩 1 byte
int d = (data[i] & 0xFF) << 16;
buf.append(MAP[(d >>> 18) & 0x3F]);
buf.append(MAP[(d >>> 12) & 0x3F]);
buf.append("==");
}
return buf.toString();
}
// ========== 解碼 ==========
private static int decodeChar(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
if (c == '=') return 0;
throw new IllegalArgumentException("Invalid Base64 char: " + c);
}
public static byte[] decode(String s) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = s.length();
int i = 0;
while (i < len) {
// 略過空白
while (i < len && s.charAt(i) <= ' ') i++;
if (i >= len) break;
int tri = (decodeChar(s.charAt(i)) << 18)
| (decodeChar(s.charAt(i+1)) << 12)
| (decodeChar(s.charAt(i+2)) << 6)
| (decodeChar(s.charAt(i+3)));
bos.write((tri >>> 16) & 0xFF);
if (s.charAt(i+2) == '=') break;
bos.write((tri >>> 8) & 0xFF);
if (s.charAt(i+3) == '=') break;
bos.write(tri & 0xFF);
i += 4;
}
byte[] result = bos.toByteArray();
bos.close();
return result;
}
// ========== 附贈工具方法 ==========
public static String[] split(String original, String sep) { /* 同前文 split 實作 */ }
public static String replace(String s, String f, String r) { /* 簡易取代 */ }
public static String removeHtml(String html) { /* 移除標籤 */ }
}
// HTTP Basic Auth
String credentials = "user:pass";
String authHeader = "Basic " + HBase64.encode(credentials.getBytes());
// 解碼伺服器回傳的 Base64 圖片
byte[] imgData = HBase64.decode(base64String);
Image img = Image.createImage(imgData, 0, imgData.length);
encode 中每 19 組(76 字元)插入 \r\n。decode 已內建略過邏輯。+/ 替換為 -_,可自行擴充 encodeUrlSafe。單一類別、零相依、標準相容的 Base64 實作,滿足 J2ME 專案中認證、資料傳輸、二進位嵌入等所有編解碼需求。