Permalink
Browse files

DecimalBigInt: conversion from arbitrary positional systems.

  • Loading branch information...
ePaul committed Mar 21, 2011
1 parent ff386de commit 2a029557f8b2ea6e2970c673e2d7451eac7ffb0e
Showing with 36 additions and 0 deletions.
  1. +36 −0 src/de/fencing_game/paul/examples/DecimalBigInt.java
@@ -91,6 +91,42 @@ public static DecimalBigInt valueOf(String decimal) {
return new DecimalBigInt(digits);
}
+ /**
+ * creates a DecimalBigInt from a string-representation
+ * in some arbitrary radix.
+ *
+ * Note: this is not the most efficient implementation, since we
+ * use the Horner scheme on DecimalBigInt values, instead working
+ * directly on {@code int[]} and convert to a DecimalBigInt only
+ * in the end.
+ *
+ * @param text the big-endian string representation of the number, using
+ * the decimal digits '0' ... '9' and additionally the latin
+ * letters 'A' ... 'Z' (or 'a' ... 'z'). (Only letters below
+ * the given radix are allowed, of course.)
+ * @param radix the radix used in the representation, between
+ * {@link Character.MIN_RADIX} (2, inclusive) and
+ * {@link Character.MAX_RADIX} (36, inclusive).
+ */
+ public static DecimalBigInt valueOf(String text, int radix) {
+ if(radix < Character.MIN_RADIX || Character.MAX_RADIX < radix) {
+ throw new IllegalArgumentException("radix out of range: " + radix);
+ }
+ DecimalBigInt bigRadix = new DecimalBigInt(radix);
+ DecimalBigInt value = new DecimalBigInt(); // 0
+ for(char digit : text.toCharArray()) {
+ int iDigit = Character.digit(digit, radix);
+ if(iDigit < 0) {
+ throw new NumberFormatException("digit " + digit +
+ " is not a valid base-"+radix+
+ "-digit.");
+ }
+ DecimalBigInt bigDigit = new DecimalBigInt(iDigit);
+ value = value.times(bigRadix).plus(bigDigit);
+ }
+ return value;
+ }
+
/**
* formats the number as a decimal String.
*/

0 comments on commit 2a02955

Please sign in to comment.