Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BaseConvertUtil {
- final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
- 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
- public static void main(String args[]) {
- System.out.println("test 10(10) do 2:"+convert("10",10,2));
- }
- public static String convert(String num, int radixFrom, int radixTo) {
- return convertHelperStr(convertHelperInt(num, radixFrom), radixTo);
- }
- public static String convertHelperStr(int i,int radix) {
- if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
- radix = 10;
- /* Use the faster version */
- if (radix == 10) {
- return Integer.toString(i);
- }
- char buf[] = new char[33];
- boolean negative = (i < 0);
- int charPos = 32;
- if (!negative) {
- i = -i;
- }
- while (i <= -radix) {
- buf[charPos--] = digits[-(i % radix)];
- i = i / radix;
- }
- buf[charPos] = digits[-i];
- if (negative) {
- buf[--charPos] = '-';
- }
- return new String(buf, charPos, (33 - charPos));
- }
- public static int convertHelperInt(String s, int radix) {
- if (s == null) {
- throw new NumberFormatException("null");
- }
- if (radix < Character.MIN_RADIX) {
- throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX");
- }
- if (radix > Character.MAX_RADIX) {
- throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX");
- }
- int result = 0;
- boolean negative = false;
- int i = 0, len = s.length();
- int limit = -Integer.MAX_VALUE;
- int multmin;
- int digit;
- if (len > 0) {
- char firstChar = s.charAt(0);
- if (firstChar < '0') { // Possible leading "+" or "-"
- if (firstChar == '-') {
- negative = true;
- limit = Integer.MIN_VALUE;
- } else if (firstChar != '+')
- throw new NumberFormatException(s);
- if (len == 1) // Cannot have lone "+" or "-"
- throw new NumberFormatException(s);
- i++;
- }
- multmin = limit / radix;
- while (i < len) {
- // Accumulating negatively avoids surprises near MAX_VALUE
- digit = Character.digit(s.charAt(i++), radix);
- if (digit < 0) {
- throw new NumberFormatException(s);
- }
- if (result < multmin) {
- throw new NumberFormatException(s);
- }
- result *= radix;
- if (result < limit + digit) {
- throw new NumberFormatException(s);
- }
- result -= digit;
- }
- } else {
- throw new NumberFormatException(s);
- }
- return negative ? result : -result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement