FileDocCategorySizeDatePackage
HexBin.javaAPI DocJava SE 5 API5472Fri Aug 26 14:55:48 BST 2005com.sun.org.apache.xerces.internal.impl.dv.util

HexBin

public final class HexBin extends Object
format validation This class encodes/decodes hexadecimal data
author
Jeffrey Rodriguez
version
$Id: HexBin.java,v 1.8 2003/05/08 20:11:55 elena Exp $

Fields Summary
private static final int
BASELENGTH
private static final int
LOOKUPLENGTH
private static final byte[]
hexNumberTable
private static final char[]
lookUpHexAlphabet
Constructors Summary
Methods Summary
public static byte[]decode(java.lang.String encoded)
Decode hex string to a byte array

param
binaryData encoded string
return
return array of byte to encode

        if (encoded == null)
            return null;
        int lengthData = encoded.length();
        if (lengthData % 2 != 0)
            return null;

        char[] binaryData = encoded.toCharArray();
        int lengthDecode = lengthData / 2;
        byte[] decodedData = new byte[lengthDecode];
        byte temp1, temp2;
        for( int i = 0; i<lengthDecode; i++ ){
            temp1 = hexNumberTable[binaryData[i*2]];
            if (temp1 == -1)
                return null;
            temp2 = hexNumberTable[binaryData[i*2+1]];
            if (temp2 == -1)
                return null;
            decodedData[i] = (byte)((temp1 << 4) | temp2);
        }
        return decodedData;
    
public static java.lang.Stringencode(byte[] binaryData)
Encode a byte array to hex string

param
binaryData array of byte to encode
return
return encoded string



     
        for (int i = 0; i<BASELENGTH; i++ ) {
            hexNumberTable[i] = -1;
        }
        for ( int i = '9"; i >= '0"; i--) {
            hexNumberTable[i] = (byte) (i-'0");
        }
        for ( int i = 'F"; i>= 'A"; i--) {
            hexNumberTable[i] = (byte) ( i-'A" + 10 );
        }
        for ( int i = 'f"; i>= 'a"; i--) {
           hexNumberTable[i] = (byte) ( i-'a" + 10 );
        }

        for(int i = 0; i<10; i++ )
            lookUpHexAlphabet[i] = (char)('0"+i);
        for(int i = 10; i<=15; i++ )
            lookUpHexAlphabet[i] = (char)('A"+i -10);
    
        if (binaryData == null)
            return null;
        int lengthData   = binaryData.length;
        int lengthEncode = lengthData * 2;
        char[] encodedData = new char[lengthEncode];
        int temp;
        for (int i = 0; i < lengthData; i++) {
            temp = binaryData[i];
            if (temp < 0)
                temp += 256;
            encodedData[i*2] = lookUpHexAlphabet[temp >> 4];
            encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf];
        }
        return new String(encodedData);