Java Hex Convert To fromHex(String s)

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

Description

from Hex

License

Apache License

Declaration

public static byte[] fromHex(String s) 

Method Source Code

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

public class Main {
    public static byte[] fromHex(String s) {
        if (s != null) {
            try {
                StringBuilder sb = new StringBuilder(s.length());
                for (int i = 0; i < s.length(); i++) {
                    char ch = s.charAt(i);
                    if (!Character.isWhitespace(ch)) {
                        sb.append(ch);/*w w  w  . j  a v a 2s  . c  om*/
                    }
                }
                s = sb.toString();
                int len = s.length();
                byte[] data = new byte[len / 2];
                for (int i = 0; i < len; i += 2) {
                    int hi = (Character.digit(s.charAt(i), 16) << 4);
                    int low = Character.digit(s.charAt(i + 1), 16);
                    if (hi >= 256 || low < 0 || low >= 16) {
                        return null;
                    }
                    data[i / 2] = (byte) (hi | low);
                }
                return data;
            } catch (Exception ignored) {
            }
        }
        return null;
    }
}

Related

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