How to convert an 18 digit numeric string to BigInteger?

喜欢而已 提交于 2019-11-28 12:08:08

You can specify the base in BigInteger constructor.

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

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);

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);
}
BigInteger bigInt = new BigInteger("9999999999999999", 16);    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!