Save This Page
Home » openejb-3.1.2-src » org.apache » openejb » util » [javadoc | source]
    1   /**
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *     http://www.apache.org/licenses/LICENSE-2.0
   10    *
   11    * Unless required by applicable law or agreed to in writing, software
   12    * distributed under the License is distributed on an "AS IS" BASIS,
   13    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    * See the License for the specific language governing permissions and
   15    * limitations under the License.
   16    */
   17   package org.apache.openejb.util;
   18   
   19   public class HexConverter {
   20   
   21       private HexConverter() {
   22           // Disallow instantiation
   23       }
   24   
   25       /**
   26        * Converts a byte array to its hexadecimal string representation, ie.
   27        * new byte[] { 127, 0, 10 } returns "7F000A".
   28        *
   29        * @param bytes an array of bytes
   30        * @return hexadecimal string representation of the first argument
   31        */
   32       public static String bytesToHex(byte[] bytes) {
   33           StringBuilder buf = new StringBuilder(bytes.length * 2);
   34           for (byte b : bytes) {
   35               buf.append(String.format("%02X", b));
   36           }
   37           return buf.toString();
   38       }
   39   
   40       /**
   41        * Converts a hexadecimal formatted string into a corresponding byte array.
   42        *
   43        * @param hexString a hexadecimal representation of a byte array
   44        * @return an array of bytes created from the input
   45        */
   46       public static byte[] hexToBytes(String hexString) {
   47           if (hexString.length() % 2 != 0) {
   48               throw new IllegalArgumentException("Invalid number of digits: input must be a string of hexadecimal digit pairs");
   49           }
   50   
   51           byte[] bytes = new byte[hexString.length() / 2];
   52           for (int i = 0; i < bytes.length; i++) {
   53               bytes[i] = (byte) Integer.parseInt(hexString.substring(i * 2, i * 2 + 2), 16);
   54           }
   55           return bytes;
   56       }
   57   
   58   }

Save This Page
Home » openejb-3.1.2-src » org.apache » openejb » util » [javadoc | source]