Java 从 int 值创建 BigInteger 实例的最有效方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2646049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the most effective way to create BigInteger instance from int value?
提问by Roman
I have a method (in 3rd-party library) with BigInteger parameter:
我有一个带有 BigInteger 参数的方法(在第 3 方库中):
public void setValue (BigInteger value) { ... }
I don't need 'all its power', I only need to work with integers. So, how can I pass integers to this method? My solution is to get string value from int value and then create BigInteger from string:
我不需要'所有的力量',我只需要处理整数。那么,如何将整数传递给这个方法呢?我的解决方案是从 int 值获取字符串值,然后从字符串创建 BigInteger:
int i = 123;
setValue (new BigInteger ("" + i));
Are there any other (recommended) ways to do that?
有没有其他(推荐的)方法可以做到这一点?
采纳答案by Michael Borgwardt
BigInteger.valueOf(i);
回答by Bozhidar Batsov
Use the static method BigInteger.valueOf(long number)
. int
values will be promoted to long
automatically.
使用静态方法BigInteger.valueOf(long number)
。int
值将被long
自动提升。
回答by Petar Minchev
You can use this static method: BigInteger.valueOf(long val)
您可以使用此静态方法: BigInteger.valueOf(long val)
回答by Paul Croarkin
setValue(BigInteger.valueOf(123L));