Java Hex to Byte Array convertHEXString2ByteArray(String value)

Here you can find the source of convertHEXString2ByteArray(String value)

Description

convert HEX String Byte Array

License

Open Source License

Declaration

public static byte[] convertHEXString2ByteArray(String value) 

Method Source Code

//package com.java2s;

public class Main {
    public static byte[] convertHEXString2ByteArray(String value) {
        if (value == null || value.length() == 0) {
            return null;
        } else {//from   w  ww .  j  a  va 2  s.  co  m
            char[] array = value.toCharArray();
            int ext = array.length % 2; // can be 0 or 1 only!
            byte[] out = new byte[array.length / 2 + ext];
            for (int i = 0; i < array.length - ext; i += 2) {
                String part = new String(array, i, 2);
                try {
                    out[i / 2] = (byte) Integer.parseInt(part, 16);
                } catch (NumberFormatException e) {
                    // ignore conversion error
                    out[i / 2] = 0;
                }
            }

            if (ext != 0) {
                String part = String.valueOf(array[array.length - 1]);
                try {
                    out[out.length - 1] = (byte) Integer.parseInt(part, 16);
                } catch (NumberFormatException e) {
                    // ignore conversion error
                    out[out.length - 1] = 0;
                }
            }
            return out;
        }
    }
}

Related

  1. convertHexAsciiToByteArray(byte[] bytes)
  2. convertHexStringToByteArray(String hexString)
  3. convertHexStringToByteArray(String s)
  4. convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte)
  5. convertHexStringToByteNoSpace(String s)