How to convert an 18 digit numeric string to BigInteger?

折月煮酒 提交于 2019-11-27 06:48:24

问题


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

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


回答1:


You can specify the base in BigInteger constructor.

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



回答2:


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

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

better, check if it starts with "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);



回答3:


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

To turn a plain string into a BigInteger

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

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

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



回答4:


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


来源:https://stackoverflow.com/questions/4416618/how-to-convert-an-18-digit-numeric-string-to-biginteger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!