Need an alternative for .parse function - java

I am currently dealing with numbers with different bases. I am using the function Long.parseLong to convert a number from base int to its decimal value:
Long.parseLong("A", 16) to convert A which is a hexadecimal to its decimal value 10. I then use Long.toString(10, 16) to convert it back to A.
The problem now is that one of the entries in the problem set is "AAAAAAAAAAAAAAAAAAA" and when I use the Long.parseLong(); function, it returns an error because the size of the conversion can't fit to a Long. I tried to use Float, but I'm afraid that there is no Float.parseFloat(String, int) with the int as its radix.
Is there an alternative which I can use?
BigInteger also doesn't have any parse function with the radix.
Any help will be much appreciated.

BigInteger has a constructor, which does radix conversion for you:
BigInteger num = new BigInteger("AAAAAAAAAAAAAAAAAAA", 16);
If you wish to convert back to hexadecimal, you can use toString:
String hex = num.toString(16);

Related

Creating a BigInteger from String and pad "0"s to it

[InputParam1:Decimal Number in String format(for Eg:30),
InputParam2:Integer to denote number of repeating 0's to append(for Eg:6)]
For converting a number from Decimal to Binary and pad digits to its front I need to perform the following steps:
Step1: BigInteger binary=new BigInteger(InputParam1,2);
-->This works when I define a BigInt with a base 16 (which I just tried when base2 failed) but not with a base 2 like above.
It throws a numberformat exception.
Step 2: String pad=StringUtils.repeat("0",InputParam2);
(to repeat 0 'InputParam2' number of times)
-->This works fine
Step 3: Need to append pad in front of binary(from Step1)
For a BigInteger, I'm not able to get something similar to .append.
So I'm trying to a)convert this BigInteger number to String and b)append pad c)convert back to BigInteger (this step I'm not able to get without creating a new BigInteger)
Any pointers on Step1 and Step3-c would be helpful please.
#1 - You haven't said what value you're passing in InputParam1, but my guess is that you're passing in something other than a string containing only '0' in '1' characters. The 'radix' parameter to the constructor tells the code how to interpret the string you're giving it. This works fine for me:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
How you construct the number has nothing to do with how you're eventually going to want to represent or display that number. The key idea here is that the representation of a number (hex, decimal, binary) has nothing to do with the number itself, just like leading zeros don't affect the value of number. 1111 binary, f hex, and 15 decimal are all the same number. If you pass the three of these into BigDecimal's constructor with a radix of 2, 16 and 10 respectively, you'll end up with EXACTLY the same thing in each case. The object will lose any notion of what kind of representation you used to set it to its initial value.
#3 - There is no concept of a number (int, BigInteger, etc.) with zero padding at the front, just as there's no notion of which base/radix you might use to represent a number visually. You can think about it conceptually, but that's just a way of displaying the number. It has nothing to do with the number itself.
I hadn't tried it before, but it seems there's no super simple way to format a binary value in Java with leading 0s, like there is for decimal and hex, since String.format() doesn't give a format specifier for binary. Per this StackOverflow post How to get 0-padded binary representation of an integer in java?, this seems to be about the best way to go, having converted the most accepted answer to work with BigInteger:
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
So here's all of my sample code, with output:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
System.out.println(str);
Output:
8
0000000000001000

How to convert String to BigInteger when var contains ".0"

I've got a String variable that may contain a number such "2015.0".
When I try to convert it to int with
int i = Integer.parseInt(myVar)
or BigInteger with
BigInteger bi = new BigInteger(myVar)
I get the error
java.lang.NumberFormatException: For input string: "2015.0"
How can I achieve a correct cast?
Thanks!
You can parse it as a BigDecimal and then convert to BigInteger
BigInteger bi = new BigDecimal("2015.0").toBigInteger()
Just note that you may lose precision information when doing this:
...any fractional part of this BigDecimal will be discarded. Note that this conversion can lose information about the precision of the BigDecimal value.
To have an exception thrown if the conversion is inexact (in other words if a nonzero fractional part is discarded), use the toBigIntegerExact() method.
As suggested in the quoted javadocs, use toBigIntegerExact() to prevent accidental losses of precision such as the one that would result from converting "2.5" to BigInteger (thanks to Ole V.V.'s comment for this remark).
You can also just parse it to a double and then drop the decimal part by casting it to int
int i = (int) Double.parseDouble(myVar);
You can't convert a float to a BigInteger, and your string has a decimal point, so it's automatically considered to be a float. You have a couple of options, but the easiest might be to strip off the decimal portion from the string to get "2015", and then use that to construct your BigInteger.
That's assuming that the decimal portion of the number doesn't matter, of course. If it does, consider using BigDecimal, instead.

Calculating decimal representation of an integer in Java

This might seem really naive but I am not sure what is the decimal representation of an integer?
Can you provide some code in Java to convert an integer to its decimal representation?
Thanks!
My answer would have been Integer.toString(value).
Done! I have now "calculated" the decimal representation of an integer (int value).
As the javadoc says:
The argument is converted to signed decimal representation and returned as a string.
Of course, they probably wanted you to write the code that implements that method, rather than using the library method.
You can use things like this :
Integer i = 10;
Double iDecimal = new Double(i);
System.out.println(iDecimal); //would print 10.0 i.e. decimal

How to convert binary fraction into hexadecimal in Java?

How can i convert a binary fraction or a decimal fraction into hex in Java?
What is the algorithm to do that?
for example i want (11.110)2 be converted into (3.C)16
and which data type do I need to hold the hex fraction ?
plz help.
Thanks.
This answer is not meant to be a complete guide on how to make a fully working program that converts from one radix to another, but it mentions most of the steps you'd have to do if you want to use the built-in methods that are available.
There are no built-in methods for converting floating-point numbers, but there are built-in methods for converting integers from/to any radix between 2-36. If you only need to convert between binary and hexadecimal and nothing else, you could also do it manually (see below the line further down), but I recommend using these methods otherwise.
If you remove the radix point . from the number (in its String-representation), you get a whole number, but keep track of how many digits were to the right of the radix point.
Here are three ways to convert a whole number from a String with any radix:
Integer.parseInt(String val, int radix) will convert to int.
Long.parseLong(String val, int radix) will convert to long.
new BigInteger(String val, int radix) will convert to BigInteger.
You should then convert the number to a double or BigDecimal, and make sure you get the radix point back in place, by dividing by the correct number. For instance, you can turn (1234)6 into (12.34)6 by dividing it by 6².
Now you are halfway done, and basically go backwards to convert the number back to a String (but with some other radix).
At the step where you want to convert from int/long/BigInteger to a String, use toString:
Integer.toString(int val, int radix) will convert from int.
Long.toString(long val, int radix) will convert from long.
val.toString(int radix) will convert from BigInteger.
Remember to insert the radix point again, and you're done.
To convert from binary to hex manually, you do the same as you would do if they were whole numbers, with few differences.
Divide the binary number into sets of 4 consecutive digits, starting at the radix point, going both left and right. Add leading/trailing zeros as needed. The rest is as explained in the link.
For instance: 101011.011 is divided into 0010 1011 . 0110 which becomes 2B.6 after converting each set to hexadecimal.

Print double as raw hex?

I'm interested in printing a double as raw hex. I don't want the mantissa and exponent interpreted.
Is there a print function in Java to accomplish it?
If not, how does one extract raw octets from a double in Java?
Use Double.doubleToLongBits() or Double.doubleToRawLongBits().
First, get the bits as long, using Double.doubleToLongBits() or Double.doubleToRawLongBits().
However if you would like to print the bits then and if you have Java 8, I would recommend converting your long to String using the new unsigned API, possibly with base 16 or 2.
double number = Math.E;
long bits = Double.doubleToRawLongBits(number);
System.out.println(Long.toUnsignedString(bits, 16)); // 4005bf0a8b145769

Categories

Resources