Java Hex Convert To fromHexString(String s)

Here you can find the source of fromHexString(String s)

Description

Decode a Hex-String to a byte Array.

License

Open Source License

Parameter

Parameter Description
s - the Hex-String to decode

Return

the byte Array

Declaration

public static byte[] fromHexString(String s) 

Method Source Code

//package com.java2s;
/**/*from w w  w  .  jav a  2  s . co m*/
 * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either version
 * 3 of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MECHANTABILITY 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 Plublic License along with this program;
 * if not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Regular Expression for HEX-Values.<br>
     * (odd number of hex-digits allowed)
     */
    public static String REGEXP_HEX = "[0-9A-Fa-f]*";

    /**
     * Decode a Hex-String to a byte Array.
     * 
     * @param s - the Hex-String to decode
     * @return the byte Array
     */
    public static byte[] fromHexString(String s) {
        if (!s.matches(REGEXP_HEX))
            throw new IllegalArgumentException("cannot parse '" + s + "'");

        int length = (int) Math.ceil(s.length() / 2.0);
        byte[] bytes = new byte[length];

        int c = s.length() - 2;
        for (int i = length - 1; i >= 0; i--) {
            bytes[i] = (byte) Integer.parseInt(s.substring(c < 0 ? 0 : c, c + 2), 16);
            c = c - 2;
        }

        return bytes;
    }
}

Related

  1. fromHexString(String input)
  2. fromHexString(String s)
  3. fromHexString(String s)
  4. fromHexString(String s)
  5. fromHexString(String s)
  6. fromHexString(String s)
  7. fromHexString(String s)
  8. fromHexString(String s)
  9. fromHexString(String s, int offset, int length)