Java Hex Convert To fromHex(byte[] hex)

Here you can find the source of fromHex(byte[] hex)

Description

Converts the given hex array to a byte array

License

Open Source License

Parameter

Parameter Description
hex the hex array

Return

the byte array

Declaration

public static byte[] fromHex(byte[] hex) 

Method Source Code

//package com.java2s;
/*// w  ww.  ja v  a2s .  c  o m
 * Copyright (c) 2009-2010 David Grant
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

public class Main {
    /**
     * Converts the given hex string to a byte array.
     * 
     * @param hex the hex string
     * @return a byte array
     */
    public static byte[] fromHex(String hex) {
        return fromHex(hex.getBytes());
    }

    /**
     * Converts the given hex array to a byte array
     * 
     * @param hex the hex array
     * @return the byte array
     */
    public static byte[] fromHex(byte[] hex) {
        byte[] bytes = new byte[hex.length / 2];

        for (int i = 0; i < bytes.length; i++) {
            int v = i * 2;
            int b = Character.digit(hex[v], 16) << 4;
            b = b | Character.digit(hex[v + 1], 16);

            bytes[i] = (byte) (b & 0xFF);
        }
        return bytes;
    }
}

Related

  1. convertHexStringToBinary(String hexString)
  2. convertHexTime2Binary(String timespan)
  3. convertHextoASCII(String text)
  4. convertHexToChar(String hex)
  5. convertHexToFloat(long hexValue)
  6. fromHex(char c)
  7. fromHex(char c)
  8. fromHex(char hi, char lo)
  9. fromHex(CharSequence cs)