1 16 17 package org.apache.xerces.impl.dv.util; 18 19 29 public final class HexBin { 30 static private final int BASELENGTH = 128; 31 static private final int LOOKUPLENGTH = 16; 32 static final private byte [] hexNumberTable = new byte[BASELENGTH]; 33 static final private char [] lookUpHexAlphabet = new char[LOOKUPLENGTH]; 34 35 36 static { 37 for (int i = 0; i < BASELENGTH; i++ ) { 38 hexNumberTable[i] = -1; 39 } 40 for ( int i = '9'; i >= '0'; i--) { 41 hexNumberTable[i] = (byte) (i-'0'); 42 } 43 for ( int i = 'F'; i>= 'A'; i--) { 44 hexNumberTable[i] = (byte) ( i-'A' + 10 ); 45 } 46 for ( int i = 'f'; i>= 'a'; i--) { 47 hexNumberTable[i] = (byte) ( i-'a' + 10 ); 48 } 49 50 for(int i = 0; i<10; i++ ) { 51 lookUpHexAlphabet[i] = (char)('0'+i); 52 } 53 for(int i = 10; i<=15; i++ ) { 54 lookUpHexAlphabet[i] = (char)('A'+i -10); 55 } 56 } 57 58 64 static public String encode(byte[] binaryData) { 65 if (binaryData == null) 66 return null; 67 int lengthData = binaryData.length; 68 int lengthEncode = lengthData * 2; 69 char[] encodedData = new char[lengthEncode]; 70 int temp; 71 for (int i = 0; i < lengthData; i++) { 72 temp = binaryData[i]; 73 if (temp < 0) 74 temp += 256; 75 encodedData[i*2] = lookUpHexAlphabet[temp >> 4]; 76 encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf]; 77 } 78 return new String (encodedData); 79 } 80 81 87 static public byte[] decode(String encoded) { 88 if (encoded == null) 89 return null; 90 int lengthData = encoded.length(); 91 if (lengthData % 2 != 0) 92 return null; 93 94 char[] binaryData = encoded.toCharArray(); 95 int lengthDecode = lengthData / 2; 96 byte[] decodedData = new byte[lengthDecode]; 97 byte temp1, temp2; 98 char tempChar; 99 for( int i = 0; i<lengthDecode; i++ ){ 100 tempChar = binaryData[i*2]; 101 temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; 102 if (temp1 == -1) 103 return null; 104 tempChar = binaryData[i*2+1]; 105 temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; 106 if (temp2 == -1) 107 return null; 108 decodedData[i] = (byte)((temp1 << 4) | temp2); 109 } 110 return decodedData; 111 } 112 } 113 | Popular Tags |