+ /**
+ * Checks if the {@link CharSequence} is a prefix of a valid number, and returns the NumberType it is a prefix of. If a String is a
+ * prefix of multiple different {@link NumberType}s, the one with the smallest radix is returned. If no valid {@link NumberType} is
+ * found, {@link NumberType#NONE} is returned.
+ *
+ * @param cs The potential prefix
+ * @return The type the {@link CharSequence} is a prefix of
+ */
+ public static NumberType prefixOfType(CharSequence cs)
+ {
+ if (isPrefix(cs, numberBin))
+ return NumberType.BINARY;
+ if (isPrefix(cs, numberOct))
+ return NumberType.OCTAL;
+ if (isPrefix(cs, numberDec))
+ return NumberType.DECIMAL;
+ if (isPrefix(cs, numberHex))
+ return NumberType.HEXADECIMAL;
+ if (isPrefix(cs, numberFloat))
+ return NumberType.FLOATINGPOINT;
+ return NumberType.NONE;
+ }
+
+ private static CharSequence extractSignAndDigits(NumberType type, CharSequence cs)
+ {
+ return type.numberPattern.matcher(cs).replaceAll("$1$2").replaceAll("_", "");
+ }
+
+ /**
+ * Computes the {@link BigInteger} value of a {@link CharSequence}, by determining the {@link NumberType} and parsing the number with
+ * the determined radix.
+ *
+ * @throws NumberFormatException if the {@link CharSequence} does not match any of the expected number patterns
+ */
+ public static BigInteger valueOf(CharSequence cs)
+ {
+ NumberType type = getType(cs);
+ if (NumberType.NONE.equals(type))
+ throw new NumberFormatException();
+ return new BigInteger(extractSignAndDigits(type, cs).toString(), type.radix);
+ }
+
+ /**
+ * Formats a {@link BigInteger} in accordance with the pattern associated with the supplied {@link NumberType}
+ */
+ public static String toString(BigInteger number, NumberType type)
+ {
+ String pattern;
+ switch (type)
+ {
+ case BINARY:
+ pattern = preferredBinPat;
+ break;
+ case OCTAL:
+ pattern = preferredOctPat;
+ break;
+ default:
+ case DECIMAL:
+ pattern = preferredDecPat;
+ break;
+ case HEXADECIMAL:
+ pattern = preferredHexPat;
+ }
+ if (number.signum() < 0)
+ return String.format(pattern, "-", number.abs().toString(type.radix));
+ return String.format(pattern, "", number.toString(type.radix));
+ }
+