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