Java Hex Convert To fromHex(String s, boolean hexIsDefault)

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

Description

from Hex

License

Open Source License

Declaration

public static int fromHex(String s, boolean hexIsDefault) 

Method Source Code

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

public class Main {
    private static final String hexReprPrefix = "0x";

    public static int fromHex(String s, boolean hexIsDefault) {
        int radix = hexIsDefault ? 16 : 10;
        int res = 0;
        int pos = 0;
        int sign = 1;
        if (s.charAt(0) == '-') {
            pos += 1;/*from w ww.j a  v a 2  s.c  o  m*/
            sign = -1;
        }
        if ((!hexIsDefault) && s.regionMatches(pos, hexReprPrefix, 0, 2)) {
            pos += 2;
            radix = 16;
        }
        int max = s.length();
        for (; pos < max; pos++) {
            int d = toDigit(s.charAt(pos));
            //System.out.println( "from hex " + s + " dig " + s.charAt( pos ) + "=" + d ) ;
            if ((d < 0) || (radix <= d))
                return res;
            res = res * radix + d;
        }
        return res * sign;
    }

    public static int fromHex(String s) {
        return fromHex(s, true);
    }

    private static int toDigit(char c) {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        return -1;
    }
}

Related

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