1 32 33 package com.imagero.uio.io; 34 35 import java.io.FilterInputStream ; 36 import java.io.IOException ; 37 import java.io.InputStream ; 38 39 42 public class HexInputStream extends FilterInputStream { 43 44 private static final char encodeTable[] = { 45 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 46 }; 47 48 public static final int decodeTable [] = new int[0x100]; 49 50 static { 51 for (int i = 0; i < decodeTable.length; i++) { 52 decodeTable[i] = -1; 53 } 54 for (int j = 0; j < encodeTable.length; j++) { 55 decodeTable[encodeTable[j]] = j; 56 } 57 } 58 59 boolean finished; 60 61 byte [] buffer = new byte[80]; 62 int count; 63 int pos; 64 65 public HexInputStream(InputStream in) { 66 super(in); 67 } 68 69 public int read() throws IOException { 70 if(pos >= count) { 71 if(finished) { 72 return -1; 73 } 74 else { 75 fillBuffer(); 76 } 77 } 78 79 int i = buffer[pos++] & 0xFF; 80 return i; 81 } 82 83 private void fillBuffer() throws IOException { 84 int k = 0; 85 for (; k < buffer.length; k++) { 86 int b0 = in.read(); 87 if (b0 == 13 || b0 == 10) { 88 k--; 89 continue; 90 } 91 if(b0 == '>') { 92 k++; 93 finished = true; 94 break; 95 } 96 int b1 = in.read(); 97 int d0 = decodeTable[b0]; 98 int d1 = decodeTable[b1]; 99 buffer[k] = (byte) (d0 * 16 + d1); 100 } 101 count = k; 102 pos = 0; 103 } 104 105 public int read(byte b[]) throws IOException { 106 return read(b, 0, b.length); 107 } 108 109 public int read(byte b[], int off, int len) throws IOException { 110 int i = off; 111 112 try { 113 for (; i < off + len; i++) { 114 int a = read(); 115 if (a == -1) { 116 i--; 117 break; 118 } 119 b[i] = (byte) a; 120 } 121 } 122 catch (IOException ex) { 123 ex.printStackTrace(); 124 } 125 return i - off; 126 } 127 } 128 | Popular Tags |