java 如何将 18 位数字字符串转换为 BigInteger?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4416618/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:16:34  来源:igfitidea点击:

How to convert an 18 digit numeric string to BigInteger?

javabiginteger

提问by Raji

Could anyone help me in converting an 18 digit string numeric to BigInteger in java

任何人都可以帮助我在 java 中将 18 位数字字符串数字转换为 BigInteger

ie;a string "0x9999999999999999"should appear as 0x9999999999999999numeric value.

即;字符串"0x9999999999999999"应显示为0x9999999999999999数值。

回答by Klark

You can specify the base in BigInteger constructor.

您可以在 BigInteger 构造函数中指定基数。

BigInteger bi = new BigInteger("9999999999999999", 16);
String s = bi.toString(16);   

回答by user85421

If the String always starts with "0x" and is hexadecimal:

如果字符串总是以“0x”开头并且是十六进制的:

    String str = "0x9999999999999999";
    BigInteger number = new BigInteger(str.substring(2));

better, check if it starts with "0x"

更好,检查它是否以“0x”开头

  String str = "0x9999999999999999";
  BigInteger number;
  if (str.startsWith("0x")) {
      number = new BigInteger(str.substring(2), 16);
  } else {
      // Error handling: throw NumberFormatException or something similar
      // or try as decimal: number = new BigInteger(str);
  }


To output it as hexadecimal or convert to an hexadecimal representation:

要将其输出为十六进制或转换为十六进制表示:

    System.out.printf("0x%x%n", number);
    // or
    String hex = String.format("0x%x", number);

回答by Peter Lawrey

Do you expect the number to be in hex, as that is what 0x usually means?

你希望数字是十六进制的,因为这就是 0x 通常的意思吗?

To turn a plain string into a BigInteger

将普通字符串转换为 BigInteger

BigInteger bi = new BigInteger(string);
String text = bi.toString();

to turn a hexidecimal number as text into a BigInteger and back.

将十六进制数字作为文本转换为 BigInteger 并返回。

if(string.startsWith("0x")) {
    BigInteger bi = new BigInteger(string.sustring(2),16);
    String text = "0x" + bi.toString(16);
}

回答by khachik

BigInteger bigInt = new BigInteger("9999999999999999", 16);