1

My assignment is to convert binary to decimal in a JLabel array without using pre-written methods (there's no user input). I have the right idea but for some reason the output is always a little bit off. I've gone through it countless times but I can't find anything wrong with my algorithm and I'm very confused as to why it doesn't produce the correct answer. I'd be very grateful if someone could help me out. Thanks!

Side note: I've read similar discussion threads regarding binary to decimal conversions but I don't understand how to do it with arrays.

Here is a snippet of my code:

   private void convert()
   {
    int[] digit = new int[8]; //temporary storage array
    int count = 0;
    for(int x = 0; x < digit.length; x++)
     {
     digit[x] = Integer.parseInt(bits[x].getText()); //bits is the original array
     count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x)); 
    }
     label.setText("" + count); 
   }
2
  • Does the digit[] store the digits of the binary number? And what does count do? Commented Mar 23, 2016 at 3:22
  • @ProgyadeepMoulik in each cell of the array there's either a 1 or a 0, so the program would convert each place value to decimal and add it all up. Count keeps track of that sum. And yes, digit[] stores the digits of the binary number. One digit per cell, and another part of my program ensures it is always randomized 0s or 1s. Commented Mar 23, 2016 at 3:24

2 Answers 2

1

You are following the binary number from left to right but are grabbing the wrong digit. You want the same digit but to multiply by the right power of two - first index being +n*128 and not +n*1

int count = 0;
for(int i = 0; i < bits.length; i++) {
    count += Integer.parseInt(bits[i].getText()) * Math.pow(2, bits.length - i - 1);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Obviously there is a bug in your snippet.

You set the digit[x], but not set the digit[length - 1 - x].

for example, x = 0, you set the digit[0], but not set digit[7].
So there will be an error when you want use the digit[length - 1 -x] here :

count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));

This the correct code here:

private void convert()
{
    int count = 0, length = 8;
    for(int i = 0; i < length; count += Integer.parseInt(bits[i].getText()) * (1 << (length - 1 - i)), i++);
    label.setText("" + count); 
}

Have not test the code. But I think it will work.

Comments

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.