Java Hex to Byte Array convertHexStringToByteArray(String s)

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

Description

convert Hex String To Byte Array

License

Open Source License

Declaration

public static byte[] convertHexStringToByteArray(String s) 

Method Source Code

//package com.java2s;

public class Main {
    public static byte[] convertHexStringToByteArray(String s) {
        s = s.replace(" 0x", "");
        s = s.replace(":0x", "");
        s = s.replace(" ", "");
        s = s.replace(":", "");
        final int len = s.length();
        final int rem = len % 2;

        byte[] ret = new byte[len / 2 + rem];

        if (rem != 0) {
            try {
                ret[0] = (byte) (Integer.parseInt(s.substring(0, 1), 16) & 0x00F);
            } catch (Exception e) {
                ret[0] = 0;//from   w  ww.  ja v  a2 s. c  om
            }
        }

        for (int i = rem; i < len; i += 2) {
            try {
                ret[i / 2 + rem] = (byte) (Integer.parseInt(s.substring(i, i + 2), 16) & 0x0FF);
            } catch (Exception e) {
                ret[i / 2 + rem] = 0;
            }
        }

        return ret;
    }
}

Related

  1. convertHexAsciiToByteArray(byte[] bytes)
  2. convertHEXString2ByteArray(String value)
  3. convertHexStringToByteArray(String hexString)
  4. convertHexStringToByteArray(String str, int numBytes, int numCharsPerByte)
  5. convertHexStringToByteNoSpace(String s)
  6. convertHexStringToBytes(String hex)
  7. convertHexStringToBytes(String hex)