Converts a string containing hexadecimal characters to a byte-array - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a string containing hexadecimal characters to a byte-array

Demo Code

/*******************************************************************************
 * Copyright (c) 2008 JCrypTool Team and Contributors
 * //from   ww  w .  j av a 2 s.  c  om
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
//package com.java2s;

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

    /**
     * Converts a string containing hexadecimal characters to a byte-array
     * 
     * @param s - a hexstring
     * 
     * @return a byte array with the corresponding value
     */
    public static byte[] fromHexString(String s) {
        byte[] rawChars = s.toUpperCase().getBytes();
        int hexChars = 0, pos = 0;

        for (int i = 0; i < rawChars.length; i++) {
            if ((rawChars[i] >= '0' && rawChars[i] <= '9')
                    || (rawChars[i] >= 'A' && rawChars[i] <= 'F')) {
                hexChars++;
            }
        }

        byte[] byteString = new byte[(hexChars + 1) / 2];

        for (int i = 0; i < rawChars.length; i++) {
            if (rawChars[i] >= '0' && rawChars[i] <= '9') {
                byteString[pos / 2] <<= 4;
                byteString[pos / 2] |= rawChars[i] - '0';
            } else if (rawChars[i] >= 'A' && rawChars[i] <= 'F') {
                byteString[pos / 2] <<= 4;
                byteString[pos / 2] |= rawChars[i] - 'A' + 10;
            } else {
                continue;
            }
            pos++;
        }

        return byteString;
    }
}

Related Tutorials