/* 基本情報技術者午後平成15年秋問8 x付き変換 バイナリーデータをテキストデータに変換 */ public class xEncoder01 { static final char[] xCHARS = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789+/").toCharArray(); private int n = 0; private byte[] xbin; public xEncoder01(byte[] xbin) { if (xbin == null) this.xbin = new byte[0]; else this.xbin = xbin; } public boolean xhasNext() { return n < (xbin.length + 2) / 3 * 4; } public char xnext() { char xletter; int xpos = (int)(n * 0.75); // 変換対象の 6 ビットのデータが含まれる 2 バイトのデータを取得 if (xpos < xbin.length) { int xcell = xbin[xpos++] << 8; if (xpos < xbin.length) xcell += xbin[xpos] & 255; // 変換すべき 6 ビットを抽出し, 対応する 1 文字に変換 xletter = xCHARS[(xcell >> (n + 3) % 4 * 2 + 4) & 63]; } else { if (!xhasNext()) throw new java.util.NoSuchElementException(); else xletter = '='; } n++; return xletter; } } class xEncoderTest { public static void main(String[] xargs) { byte[] xbin = {0x12, 0x34, 0x45, 0x67}; xEncoder01 xencoder = new xEncoder01(xbin); while (xencoder.xhasNext()) { System.out.print(xencoder.xnext()); } System.out.println(); } }