format an hexastring 0xXXXXXXXX or #XXXXXXXX to an int - Android java.lang

Android examples for java.lang:Hex

Description

format an hexastring 0xXXXXXXXX or #XXXXXXXX to an int

Demo Code

public class Main {

  public static int intFromHexString(String hexa) throws NumberFormatException {
    int radix = 16;
    int index = 0;
    int result = 0;

    // Handle radix specifier, if present
    if (hexa.startsWith("0x", index) || hexa.startsWith("0X", index)) {
      index += 2;//www . j a  va  2  s . co  m
      radix = 16;
    } else if (hexa.startsWith("#", index)) {
      index++;
      radix = 16;
    }
    if (hexa.length() - index > 8) {
      throw new NumberFormatException(hexa + " exceeds 8 digits");
    }
    int digit = 0;
    for (int i = index; i < hexa.length(); i++) {
      result = result << 4;
      digit = Character.digit(hexa.charAt(i), radix);
      if (digit == -1) {
        throw new NumberFormatException(hexa + " : \'" + hexa.charAt(i) + "\' is not a valid hex digit");
      }
      result |= digit;
    }
    return result;
  }

}

Related Tutorials