1 30 31 34 package com.nightlabs.math; 35 36 import java.util.HashMap ; 37 import java.util.Map ; 38 39 42 public class BaseNCoder 43 { 44 private int base; 45 private char[] symbols = null; 46 private Map symbolMap = new HashMap (); 47 48 protected BaseNCoder() 49 { 50 } 51 52 57 public BaseNCoder(char[] digitSymbols) 58 { 59 init(digitSymbols); 60 } 61 62 67 protected void init(char[] digitSymbols) 68 { 69 this.symbols = digitSymbols; 70 base = digitSymbols.length; 71 symbolMap.clear(); 72 for (int i = 0; i < digitSymbols.length; ++i) { 73 char c = digitSymbols[i]; 74 symbolMap.put(new Character (c), new Integer (i)); 75 } 76 } 77 78 public String encode(long number, int minDigitCount) 79 { 80 if (symbols == null) 81 throw new IllegalStateException ("symbols undefined! Call init(...) first!"); 82 83 boolean numberStarted = false; 84 int digitCount = number < base ? 1 : 1 + (int)MathUtil.log(base, number); 85 long divisor; 86 int digitValue; 87 StringBuffer res = new StringBuffer (); 88 for (int digitIdx = digitCount - 1; digitIdx >= 0; --digitIdx) { 89 divisor = (long)Math.pow(base, digitIdx); 90 digitValue = (int)(number / divisor); 91 if (numberStarted || digitIdx < minDigitCount || digitValue > 0) { 92 numberStarted = true; 93 number = number - (long)(digitValue * divisor); 94 res.append(symbols[digitValue]); 95 } 96 } 97 return res.toString(); 98 } 99 100 public long decode(String s) 101 { 102 if (symbols == null) 103 throw new IllegalStateException ("symbols undefined! Call init(...) first!"); 104 105 int digitIdx = 0; 106 long res = 0; 107 for (int i = s.length() - 1; i >= 0; --i) { 108 char c = s.charAt(i); 109 Integer digitValue = (Integer ) symbolMap.get(new Character (c)); 110 if (digitValue == null) 111 throw new NumberFormatException ("Unknown digit: "+c); 112 113 res = res + ((long)digitValue.intValue()) * (long)Math.pow(base, digitIdx); 114 ++digitIdx; 115 } 116 return res; 117 } 118 119 122 public int getBase() 123 { 124 return base; 125 } 126 } 127 | Popular Tags |