Mega Code Archive

 
Categories / Java / Development Class
 

Encode Hex

/*  * @(#)$Id: StringUtils.java 3619 2008-03-26 07:23:03Z yui $  *  * Copyright 2006-2008 Makoto YUI  *  * Licensed under the Apache License, Version 2.0 (the "License");  * you may not use this file except in compliance with the License.  * You may obtain a copy of the License at  *  *     http://www.apache.org/licenses/LICENSE-2.0  *  * Unless required by applicable law or agreed to in writing, software  * distributed under the License is distributed on an "AS IS" BASIS,  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  * See the License for the specific language governing permissions and  * limitations under the License.  *   * Contributors:  *     Makoto YUI - initial implementation  */ //package xbird.util.string; /**  *   * <DIV lang="en"></DIV>  * <DIV lang="ja"></DIV>  *   * @author Makoto YUI (yuin405+xbird@gmail.com)  */ public final class StringUtils {     private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();     private static final int UPPER_NIBBLE_MASK = 0xF0;     private static final int LOWER_NIBBLE_MASK = 0x0F;     public static void encodeHex(final byte b, final StringBuilder buf) {         final int upper = (b & UPPER_NIBBLE_MASK) >> 4;         final int lower = b & LOWER_NIBBLE_MASK;         buf.append(HEX_DIGITS[upper]);         buf.append(HEX_DIGITS[lower]);     }     public static String encodeHex(final byte[] buf) {         final int buflen = buf.length;         final char[] ch = new char[buflen * 2];         for(int i = 0, j = 0; i < buf.length; i++, j += 2) {             final byte b = buf[i];             final int upper = (b & UPPER_NIBBLE_MASK) >> 4;             final int lower = b & LOWER_NIBBLE_MASK;             ch[j] = HEX_DIGITS[upper];             ch[j + 1] = HEX_DIGITS[lower];         }         return new String(ch);     }     public static byte[] decodeHex(final char[] data) {         final int len = data.length;         if((len & 0x01) != 0) {             throw new IllegalArgumentException("Illegal HexaDecimal character");         }         final byte[] out = new byte[len >> 1];         for(int i = 0, j = 0; j < len; i++) {             int f = hexToDigit(data[j], j) << 4;             j++;             f = f | hexToDigit(data[j], j);             j++;             out[i] = (byte) (f & 0xFF);         }         return out;     }     private static int hexToDigit(final char ch, final int index) {         final int digit = Character.digit(ch, 16);         if(digit == -1) {             throw new IllegalArgumentException("Illegal HexaDecimal character '" + ch                     + "' at index " + index);         }         return digit;     } }