Java Hex Convert To fromHex(String s)

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

Description

from Hex

License

Open Source License

Declaration

public static byte[] fromHex(String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static byte[] fromHex(String s) {
        if (s.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex " + s + " must be divisible by two");
        }/*w  w w  .  j  a  v  a  2  s.c  o  m*/
        byte[] bytes = new byte[s.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            char left = s.charAt(i * 2);
            char right = s.charAt(i * 2 + 1);
            byte b = (byte) ((getValue(left) << 4) | (getValue(right) & 0xF));
            bytes[i] = b;
        }
        return bytes;
    }

    private static int getValue(char c) {
        int i = Character.digit(c, 16);
        if (i < 0) {
            throw new IllegalArgumentException("Invalid hex char: " + c);
        }
        return i;
    }
}

Related

  1. fromHex(String input, int max)
  2. fromHex(String s)
  3. fromHex(String s)
  4. fromHex(String s)
  5. fromHex(String s)
  6. fromHex(String s)
  7. fromHex(String s)
  8. fromHex(String s, boolean hexIsDefault)
  9. fromHex(String src)