gpt4 book ai didi

java - Java 中的 PHP base_convert

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:00 27 4
gpt4 key购买 nike

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

最佳答案

经过一番摆弄和 @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);
}

关于java - Java 中的 PHP base_convert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com