I'm trying to work with some larger integer values but I'm having some issues initializing my BigInteger variable. I've been doing:
BigInteger x = new BigInteger("" + (Math.pow(2, n)));
Where n is some number in the 100s, but this is throwing a NumberFormatException. I don't think I can use BigInteger,Valueof() because that takes a long which i don't believe is big enough. Any help would be appreciated.
One way or another Math.pow returns a value of type double which will be formatted with a decimal separator. BigInteger cannot accept decimal values.
Throws:
NumberFormatException - val is not a valid representation of a BigInteger.
Just use the pow method provided by BigInteger
BigInteger x = BigInteger.TWO.pow(n);
Related
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.
Because:
The int data type is a 32-bit signed two's complement integer. It has
a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
Code Throwing the NumberFormatException:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?
Use BigInteger to avoid numeric limits of primitive int and long:
BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16); // Radix 16 indicates hex
System.out.println(x16);
The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.
Demo.
If your input value can be arbitrarily large, then #dasblinkenlight's answer involving BigInteger is your best bet.
However, if your value is less than 263, then you can just use Long instead of Integer:
String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex); // 2540be3ff
Live demo.
Use Integer.parseUnsignedInt
When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:
int n = Integer.parseUnsignedInt("CAFEBABE", 16);
(I used hexadecimal here, as it is easier to see that above we are just in that range.)
However 9_999_999_999 is above the unsigned int range too.
Try this way:
String largeNumberAsAString = "9999999999";
System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));
I know that integers have Integer.parseInt(string, 2); but when the value of the decimal is very large, how can we use BigInteger in this case?
BigInteger(giantBinaryString, 2);
There's a constructor for that.
Use the constructor BigInteger(String s)
documentation: http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html
For a binary integer represented as a string, use
BigInteger(binaryString, 2);
In this case you can construct a BigInteger from a string which
denotes a very very large integer. This is the purpose of BigInteger.
If you don't use BigInteger it will overflow your int variable.
You can do this by calling.
BigInteger b = new BigInteger(str, radix);
where you pass in radix = 2 or radix = 10 or whatever
you need (seems you need 2 in your case) and str is the value.
Then you can use
b.toString(radix);
to output your BigInteger value in whatever radix you want.
I think you are looking for this BigInteger(binaryString, 2);
Why does this code throw NumberFormatException?
int a = Integer.parseInt("1111111111111111111111111111111111111111");
How to get the value of int for that String?
The value that you're attempting to parse is much bigger than the biggest allowable int value (Integer.MAX_VALUE, or 2147483647), so a NumberFormatException is thrown. It is bigger than the biggest allowable long also (Long.MAX_VALUE, or 9223372036854775807L), so you'll need a BigInteger to store that value.
BigInteger veryBig = new BigInteger("1111111111111111111111111111111111111111");
From BigInteger Javadocs:
Immutable arbitrary-precision integers.
This is because the number string is pretty large for an int . Probably this requires a BigInteger .
There is no integer value for that string. That's why it's throwing an exception. The maximum value for an integer is 2147483647, and your value clearly exceeds that.
I'm trying to use BigInteger values along side Math.Log10 method.
final BigInteger answerNo = fact;
final int digits = 1 + (int)Math.floor(Math.log10(answerNo));
Unfortunately the compiler says incompatible types.
If I change the ints to BigIntegers it still doesn't like it.
Instead of doing a log10 you can find the number of digits by simply doing:
int digits = answerNo.toString().length();
You can't assign an int to a BigInteger - you could write: final BigInteger answerNo = BigInteger.valueOf(fact);
Mat.log10 expects a double, not a BigInteger
If you don't mind a loss of precision, you could simply use doubles:
final int digits = 1 + (int)Math.floor(Math.log10(fact));
If you care about precision, you will need to calculate the log manually.
BigInteger.toString() can be inefficient in terms of memory if you only care for count of digits.
You can instead try converting BigInteger into a BigDecimal and use the BigDecimal.precision() to achieve the same. See this answer for details.
I am getting a number format exception when trying to do it
int temp = Integer.parseInt("C050005C",16);
if I reduce one of the digits in the hex number it converts but not otherwise. why and how to solve this problem?
This would cause an integer overflow, as integers are always signed in Java. From the documentation of that method (emphasis mine):
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
The value represented by the string is not a value of type int.
It would fit into an unsigned integer, though. As of Java 8 there's Integer.parseUnsignedInt (thanks, Andreas):
int temp = Integer.parseIntUnsigned("C050005C",16);
On earlier Java versions your best bet here might to use a long and then just put the lower 4 bytes of that long into an int:
long x = Long.parseLong("C050005C", 16);
int y = (int) (x & 0xffffffff);
Maybe you can even drop the bitwise "and" here, but I can't test right now. But that could shorten it to
int y = (int) Long.parseLong("C050005C", 16);
C050005C is 3226468444 decimal, which is more than Integer.MAX_VALUE. It won't fit in int.
Use this:
long temp = Long.parseLong("C050005C",16);
The signed int type ranges from 0x7FFFFFFF to -0x80000000.