Java中的PHP base_convert

时间:2014-01-19 04:20:16

标签: java php

是否有一种很好的方法可以在与PHP base_convert函数兼容的方式中在Java中进行基数转换?我一直在玩布尔数组,但这似乎是解决这个问题的一个非常复杂的解决方案。

3 个答案:

答案 0 :(得分:1)

经过@BoristheSpider的一些摆弄和建议之后,这个答案似乎正常工作,包括与PHP中的32位整数相关的溢出问题。

/**
 * Converts a string from one base to another base. The bases must be between
 * 2 and 36 inclusive. This function exhibits the same issues as the original
 * PHP version related to overflow in 32 bit integers.
 * 
 * @param inputValue A string representation of a number.
 * @param fromBase The starting radix of a number between 2 and 36 inclusive.
 * @param toBase The ending radix of the number between 2 and 36 inclusive.
 * @return The <code>inputValue</code> converted into <code>toBase</code> base.
 * @see http://www.php.net/manual/en/function.base-convert.php
 */
public static String base_convert(final String inputValue, final int fromBase, final int toBase) {
    if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36) {
        return null;
    }
    String ret = null;
    try {
        ret = Integer.toString(Integer.parseInt(inputValue, fromBase), toBase);
    } catch(Exception ex) {};
    return ret;
}

对于奖励积分,可以轻松包装此功能以提供PHP的bindecdecbin功能:

/**
 * Converts a decimal string into a binary string.
 * 
 * @param inputValue A string representation of a decimal number.
 * @return A bit string representation of the <code>inputValue</code>.
 */
public static String decbin(final String inputValue) {
    return Util.base_convert(inputValue, 10, 2);
}
/**
 * Converts a binary string into a decimal string.
 * 
 * @param inputValue A string representation of a binary number.
 * @return A decimal number string representation of the <code>inputValue</code>.
 */
public static String bindec(final String inputValue) {
    return Util.base_convert(inputValue, 2, 10);
}

答案 1 :(得分:0)

你试过吗?

  public static String base_convert(final String inputValue, final int fromBase, final int toBase) {
    return new BigInteger(inputValue, fromBase).toString(toBase);
  }

看起来更多&#34; java方式&#34;对我来说:))

答案 2 :(得分:0)

感谢@jwriteclub。

但有时我们需要替换非数字。

    public static String base_convert(final String inputValue, final int fromBase, final int toBase) {
    if (StringUtils.isEmpty(inputValue))
        return inputValue;

    if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36) {
        return null;
    }
    String ret = null;

    final String numberInputValue = inputValue.replaceAll("\\D", "");

    try {
        Integer in=Integer.parseInt(numberInputValue, fromBase);
        ret = Integer.toString(in, toBase);
    } catch (Exception ignored) {
    }

    return ret;
}