如何将大数从一个基数转换为另一个基数 [英] How to convert big numbers from one base to another
问题描述
我正在尝试将SQL函数转换为Groovy以便在Elasticsearch中使用,但是我仍然停留在这个阶段.考虑到我一生中从未接触过Java或Groovy,我在做什么错了?
I am trying to convert a SQL function into Groovy for usage in Elasticsearch, but I am stuck at this stage. Considering, I have never touched java or groovy in my life, what am I doing wrong?
代码
public String convertFromBaseToBase(String str, int fromBase, int toBase) {
return Integer.toString(Integer.parseInt(str, fromBase), toBase);
}
output = convertFromBaseToBase("8f8f87878f8f8080", 16, 10);
System.out.print(output);
错误
java.lang.NumberFormatException:对于输入字符串:"8f8f87878f8f8080"
在java_lang_Integer $ parseInt.call(未知来源)
在Script1.convertFromBaseToBase(Script1.groovy:2)
在Script1.run(Script1.groovy:5)
java.lang.NumberFormatException: For input string: "8f8f87878f8f8080"
at java_lang_Integer$parseInt.call(Unknown Source)
at Script1.convertFromBaseToBase(Script1.groovy:2)
at Script1.run(Script1.groovy:5)
推荐答案
8f8f87878f8f8080
是一个非常大的数字(十进制10344635885392199808
),并且不适合Integer
内.
8f8f87878f8f8080
is a very big number (10344635885392199808
in decimal), and will not fit inside an Integer
.
对于如此大的数字,您将不得不使用BigInteger
.
You will have to use BigInteger
for such big numbers.
public static String convertFromBaseToBase (String str, int fromBase, int toBase){
return (new BigInteger(str, fromBase)).toString(toBase);
}
工作代码-->
https://www.onlinegdb.com/B1mMEcKPX
BigInteger -->
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString(int)
BigInteger -->
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString(int)
这篇关于如何将大数从一个基数转换为另一个基数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!