Converts an hex string to a byte array. - Java java.lang

Java examples for java.lang:String Hex

Description

Converts an hex string to a byte array.

Demo Code

/**// ww  w  . j  ava  2 s  .c  om
 * 
 * Copyright (C) 2004-2008 FhG Fokus
 *
 * This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation
 * with some additional features
 *
 * You can redistribute the FhG Fokus UPnP stack and/or modify it
 * under the terms of the GNU General Public License Version 3 as published by
 * the Free Software Foundation.
 *
 * For a license to use the FhG Fokus UPnP stack software under conditions
 * other than those described here, or to purchase support for this
 * software, please contact Fraunhofer FOKUS by e-mail at the following
 * addresses:
 *   upnpstack@fokus.fraunhofer.de
 *
 * The FhG Fokus UPnP stack is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String data = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(binHexToByteArray(data)));
    }

    /**
     * Converts an hex string to a byte array. '-','_',' ',':' are removed prior to the conversion. data.length mod 2 must
     * be 0
     */
    public static byte[] binHexToByteArray(String data) {
        if (data == null) {
            return null;
        }

        // remove hyphens
        data = data.replaceAll("-", "");
        data = data.replaceAll("_", "");
        data = data.replaceAll(" ", "");
        data = data.replaceAll(":", "");

        if (data.length() % 2 != 0) {
            return null;
        }

        try {
            byte[] result = new byte[data.length() / 2];

            for (int i = 0; i < data.length() / 2; i++) {
                String valueString = data.substring(i * 2, (i + 1) * 2);
                result[i] = (byte) Integer.parseInt(valueString, 16);
            }
            return result;
        } catch (Exception e) {
        }
        return null;
    }
}

Related Tutorials