Java Hex Convert To fromHexString(String s)

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

Description

from Hex String

License

Apache License

Declaration

public static byte[] fromHexString(String s) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private static final String HEX_STRING = "0123456789abcdef";

    public static byte[] fromHexString(String s) {
        if (s.length() % 2 == 1) {
            throw new IllegalArgumentException("Invalid length of string.");
        }// w w  w. j  a  v a 2s  .c  o m
        byte[] data = new byte[s.length() / 2];
        for (int i = 0; i < data.length; i++) {
            char c1 = s.charAt(i * 2);
            char c2 = s.charAt(i * 2 + 1);
            int n1 = HEX_STRING.indexOf(c1);
            int n2 = HEX_STRING.indexOf(c2);
            if (n1 == (-1)) {
                throw new IllegalArgumentException("Invalid char in string: " + c1);
            }
            if (n2 == (-1)) {
                throw new IllegalArgumentException("Invalid char in string: " + c2);
            }
            int n = (n1 << 4) + n2;
            data[i] = (byte) n;
        }
        return data;
    }
}

Related

  1. fromHexString(String in)
  2. fromHexString(String input)
  3. fromHexString(String input)
  4. fromHexString(String input)
  5. fromHexString(String s)
  6. fromHexString(String s)
  7. fromHexString(String s)
  8. fromHexString(String s)
  9. fromHexString(String s)