0

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

1
  • Assignment, you can try out urself.. by the way, Java Class name is desired to be BinToDec and not binToDec Commented Jul 9, 2014 at 22:51

2 Answers 2

3

There are 2 problems with your code.

  1. 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;
    
  2. 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);
    
Sign up to request clarification or add additional context in comments.

4 Comments

Your answer is better than mine, but one edit: it should be "there are more than 32 bits in your binary string".
@Jashaszun In Java, ints are signed, so using that most significant 32nd bit will cause overflow (if it's set). In fact, using long just puts off the problem, as this will still have an overflow problem if there are more than 63 bits represented in the binary string.
Thank you so much for answering and explaining! Got it to work perfectly!
@rgettman Ah right, of course! I can't believe I didn't get that by myself.
0

It won't work because int in Java is 32-bit, and your binary string there has 36 bits. This will result in overflow.

2 Comments

what types can I use?
Long, because it's 64-bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.