Java Hex to Byte Array convertHexStringToBytes(String hex)

Here you can find the source of convertHexStringToBytes(String hex)

Description

Converts a hexadecimal String (such as one generated by the #convertBytesToHexString(byte[]) method) into an array of bytes.

License

Apache License

Parameter

Parameter Description
hex The hexadecimal String to be converted into an array of bytes.

Return

An array of bytes that.

Declaration

public static byte[] convertHexStringToBytes(String hex) 

Method Source Code

//package com.java2s;
//   Licensed under the Apache License, Version 2.0 (the "License");

public class Main {
    /**// w  w  w .j a  va2  s . c om
     * Converts a hexadecimal String (such as one generated by the
     * {@link #convertBytesToHexString(byte[])} method) into an array of bytes.
     * @param hex The hexadecimal String to be converted into an array of bytes.
     * @return An array of bytes that.
     */
    public static byte[] convertHexStringToBytes(String hex) {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex string must have even number of characters.");
        }
        byte[] seed = new byte[hex.length() / 2];
        for (int i = 0; i < seed.length; i++) {
            int index = i * 2;
            seed[i] = (byte) Integer.parseInt(hex.substring(index, index + 2), 16);
        }
        return seed;
    }
}

Related

  1. convertHEXString2ByteArray(String value)
  2. convertHexStringToByteArray(String hexString)
  3. convertHexStringToByteArray(String s)
  4. convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte)
  5. convertHexStringToByteNoSpace(String s)
  6. convertHexStringToBytes(String hex)
  7. convertHexToByteArray(String hexString)
  8. convertHexToBytes(String s)
  9. convertHexToBytes(String s)