Reputation: 13
Need a bit of help here:
I was assigned a project to convert a Hex values in a file to Decimal using Java without using methods available in Java that can do this directly(we have to do it the long way).
I have converted my Hex values to Binary successfully but am having trouble converting the Binary strings to Decimal. The output is not correct; I only need help in this section so I just put the first binary value I need to convert to make things simple to understand and explain. Here is what I have so far
public class binToDec {
public static void main(String[] args) {
int decimal = 0;
String binary = "101010111100110111101111101010111100";
for (int pow = (binary.length()-1); pow > -1; pow--) {
if (binary.charAt(pow)=='1'){
decimal += (Math.pow(2, pow));
}
}
System.out.print(decimal);
}
}
run: 2147483647 //this is incorrect. it should be 46118402748
Thank you so much for your help
Upvotes: 0
Views: 3406
Reputation: 178263
There are 2 problems with your code.
Overflow is certainly occurring, because an int
can hold only a value up to 2^31 - 1, and there are more than 31 bits in your binary
string. Declare decimal
to be a long
.
long decimal = 0;
You are applying the exponent from the wrong end of your loop when adding to decimal
. The 0
char is the most significant, but you are sending in an exponent of 0
, as if it was the least significant. Try
decimal += (Math.pow(2, (len - pow - 1)));
(This assumes len
is declared as int len = binary.length();
.)
Using Math.pow
could be considered overkill. You can also try
decimal += 1L << (len - pow - 1);
Upvotes: 3
Reputation: 9270
It won't work because int
in Java is 32-bit, and your binary string there has 36 bits. This will result in overflow.
Upvotes: 0